Control Structures in Python Programming Language — Conditional Statements (if) and Loops

Nuwan Abeywickrama
5 min readOct 28, 2024

--

Welcome to the second article in the Python learning series! Now that you understand Python’s basics, let’s explore control structures. Control structures allow us to control the flow of programs, making them dynamic, responsive, and versatile.

In this article, I’ll cover the essentials of Python’s control structures, including conditional statements, loops, and keywords like break, continue, and pass. By the end, you’ll be able to make decisions in your code and iterate through data efficiently.

  1. Introduction to Control Structures
  2. Conditional Statements (if, elif, else)
  3. Loops (for, while)
  4. Control Flow Keywords (break, continue, pass)
  5. Practical Examples

1. Introduction to Control Structures

Control structures determine the order in which code executes. They allow programs to react to conditions and iterate over sequences, such as lists and ranges. Python provides two primary types of control structures —conditional statements and loops.

2. Conditional Statements.

Conditional statements in Python, namely if, elif, and else, allow the program to make decisions based on certain conditions.

The “ if ” statement checks a condition and if it evaluates to True executes the indented code block. elif (short for "else if") and else provide alternative code blocks to run if the initial condition is False.

temperature = 25

if temperature > 30:
print("It's hot outside.")
elif temperature > 20:
print("It's warm outside.")
else:
print("It's cold outside.")

Let’s understand the above code.

The program first checks if the temperature is greater than 30. If true, it prints “It’s hot outside.”
If not, it checks if the temperature is greater than 20. If true, it prints “It’s warm outside.”
If both conditions are false, it executes the else block and prints “It’s cold outside.”

  • Conditions use comparison operators (==, !=, >, <, >=, <=) and logical operators (and, or, not) to combine multiple conditions.
  • Indentation defines the code block under each condition.

Chaining Comparisons
Python allows chaining comparisons, which is common in certain conditions.

age = 18
if 18 <= age < 65:
print("Working age")

Compound Conditions
Use and, or, and not to combine multiple conditions.

temperature = 25
good_oxygen_level = True

if temperature > 20 and good_oxygen_level:
print("Comfortable Environment")

3. Loops.

Loops are used to repeat a block of code multiple times. Python has two main types of loops: for and while.

a. for Loop
The for loop iterates over a sequence (lists, tuples, sets, dictionaries, range, and strings) and executes a code block for each element in the sequence.

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
print(fruit)

# Output:
# apple
# banana
# cherry


for letter in "SampleText":
print(letter) # Outputs each character in the string

Looping with enumerate
This function provides both the index and the item, which is helpful in some cases.

fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(index, fruit) # Outputs index and fruit

Range with Step
The range() function can take a third parameter for a step, which can be useful for custom increments.

for i in range(0, 10, 2):  
print(i) # Outputs 0, 2, 4, 6, 8

b. while Loop
The while loop repeats as long as a given condition is True. Be careful with while loops, as they can create infinite loops if the condition never becomes False.

count = 5

while count > 0:
print(count)
count -= 1 # Decrease count by 1 each time

print("END LOOP")

# OUTPUT:
# 5
# 4
# 3
# 2
# 1
# END LOOP

while Loop with else
In Python, the while loop can have an accompanying else block, which runs if the loop completes normally (without encountering a break statement). This is useful for checking if the loop ran to completion.

count = 0
while count < 5:
print(count)
count += 1
else:
print("Loop completed without break")

# OUTPUT:
# 0
# 1
# 2
# 3
# 4
# Loop completed without break

Choosing Between for and while
Use for when the number of iterations is known or if iterating over a sequence.
Use while when the number of iterations depends on a dynamic condition.

4. Control Flow Keywords.

Python provides several keywords to control loop behavior. Such as break, continue, and pass.

a. break
break
exits the loop immediately, skipping any remaining iterations.

for i in range(10):
if i == 5: # In this example, the loop stops when i reaches 5, so numbers from 5 onward are not printed.
break
print(i)


# OUTPUT:
# 0
# 1
# 2
# 3
# 4

b. continue
continue
skip the current iteration and move to the next one.

for i in range(10):
if i == 5: # Here, the loop skips over even numbers by using continue.
continue
print(i)

# OUTPUT
# 0
# 1
# 2
# 3
# 4
# 6
# 7
# 8
# 9

c. pass
pass
is a placeholder that does nothing but can be used to define an empty code block when required.
The pass statement is beneficial when writing code you intend to complete later or as a placeholder for code under construction.

for i in range(10):
if i == 5:
pass # No action taken when i is 3, just a placeholder
print(i)

# OUTPUT:
# 0
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9

5. Practical Examples

Example 1 — Grade Evaluation with Conditions and Loops

grades = [85, 70, 92, 60, 78]

for grade in grades:
if grade >= 90:
print("Grade A")
elif grade >= 80:
print("Grade B")
elif grade >= 70:
print("Grade C")
elif grade >= 60:
print("Grade D")
else:
print("Grade F")

Example 2 — Validating User Input

password = input("Enter a password of at least 6 characters: ")

while len(password) < 6:
print("Password too short. Please try again.")
password = input("Enter a password of at least 6 characters: ")

print("Password accepted.")

Example 3 — Summing Numbers Until a Condition is Met

total = 0
number = 1

while total < 50:
total += number
number += 1
print("Total reached:", total)

Example 4 — Searching for a Value in a List

names = ["Alice", "Bob", "Charlie", "Diana"]

search_name = "Charlie"
found = False

for name in names:
if name == search_name:
found = True
break

if found:
print(f"{search_name} was found in the list.")
else:
print(f"{search_name} was not found in the list.")

Example 5 — Prime Number Check

number = 17
is_prime = True
i = 2

if number <= 1: # 0, 1, and negative numbers are not prime
is_prime = False
else:
while i * i <= number:
if number % i == 0:
is_prime = False
break
i += 1

if is_prime:
print(f"{number} is a prime number.")
else:
print(f"{number} is not a prime number.")

Mastering control structures allows you to make decisions in your code and handle repeated actions efficiently. With the knowledge you’ve gained here, you can start building dynamic programs that respond to user input, process data, and more.

Stay tuned for the next article in this series, where I’ll cover functions in Python. You will learn how to modularize code for better organization and reuse.

👉 Getting Started with Python: Understanding Syntax, Variables, and Data Types.

Github Repo: https://github.com/Nuwan-Abeywickrama/python-learn/tree/master

You can follow me for upcoming articles. 🔔

The comment section is open for you to share special things, and new updates, and mention mistakes regarding this content. I’m also learning new things from your comments.
Sharing knowledge, learning new things, and helping others will help to develop a better world. Let’s share our knowledge to learn for everyone.🏆🏆🥇

Thank You. 🤝🤝

--

--

Nuwan Abeywickrama
Nuwan Abeywickrama

Written by Nuwan Abeywickrama

Software QA Engineer | Tech & Science Enthusiast | Health Science Enthusiast

No responses yet