Control Flow: if, for, and while in Python
Conditional Statements: if, elif, else
The if statement runs a block of code only when a condition is True:
temperature = 35
if temperature > 30:
print("It's hot outside.")
Python uses indentation (4 spaces by convention) to define blocks. There are no curly braces or end keywords — the indentation itself is the structure.
Adding Alternatives with elif and else
score = 72
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(f"Score: {score}, Grade: {grade}")
# Score: 72, Grade: C
Python evaluates conditions top to bottom and executes the first block that matches. The else block catches everything that did not match any earlier condition. Both elif and else are optional.
Combining Conditions
Use and, or, and not to build compound conditions:
age = 25
has_license = True
if age >= 16 and has_license:
print("You can drive.")
if age < 13 or age > 65:
print("Discounted ticket available.")
if not has_license:
print("You need a license first.")
These logical operators short-circuit: with and, Python stops evaluating as soon as it hits a False; with or, it stops at the first True.
For Loops
A for loop iterates over a sequence — a list, string, range, or any iterable:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
Looping with range()
range() generates a sequence of numbers. It is the standard way to loop a specific number of times:
for i in range(5):
print(i)
# 0, 1, 2, 3, 4
range() accepts up to three arguments: range(start, stop, step):
# Count from 2 to 10 in steps of 2
for n in range(2, 11, 2):
print(n)
# 2, 4, 6, 8, 10
The stop value is exclusive — range(2, 11, 2) produces numbers up to but not including 11.
Iterating Over Strings
Strings are sequences, so you can loop through each character:
for char in "Python":
print(char, end=" ")
# P y t h o n
Using enumerate()
When you need both the index and the value, use enumerate():
colors = ["red", "green", "blue"]
for index, color in enumerate(colors):
print(f"{index}: {color}")
# 0: red
# 1: green
# 2: blue
While Loops
A while loop repeats as long as its condition remains True:
count = 0
while count < 5:
print(f"Count is {count}")
count += 1
Output:
Count is 0
Count is 1
Count is 2
Count is 3
Count is 4
Always ensure the condition will eventually become False. Forgetting to update the loop variable creates an infinite loop that hangs your program.
Practical Example: User Input Loop
A common pattern is looping until valid input is received:
while True:
user_input = input("Enter a positive number: ")
if user_input.isdigit() and int(user_input) > 0:
print(f"You entered {user_input}.")
break
print("Invalid input. Try again.")
break and continue
break — Exit the Loop Immediately
break terminates the nearest enclosing loop:
for number in range(1, 100):
if number * number > 50:
print(f"{number} is the first integer whose square exceeds 50.")
break
# 8 is the first integer whose square exceeds 50.
continue — Skip to the Next Iteration
continue skips the rest of the current iteration and jumps to the next one:
for i in range(10):
if i % 3 == 0:
continue # skip multiples of 3
print(i, end=" ")
# 1 2 4 5 7 8
Use continue to avoid deep nesting. Instead of wrapping logic in an if block, skip the cases you do not want and keep the main logic at a shallow indentation level.
Nested Loops
You can place loops inside other loops. The inner loop runs completely for each iteration of the outer loop:
for row in range(1, 4):
for col in range(1, 4):
print(f"({row},{col})", end=" ")
print() # newline after each row
Output:
(1,1) (1,2) (1,3)
(2,1) (2,2) (2,3)
(3,1) (3,2) (3,3)
Multiplication Table Example
size = 5
for i in range(1, size + 1):
for j in range(1, size + 1):
print(f"{i * j:4}", end="")
print()
Output:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
The format specifier :4 pads each number to 4 characters wide, keeping the columns aligned.
The else Clause on Loops
Python allows an else block after for and while loops. The else block runs only if the loop completed without hitting a break:
numbers = [2, 4, 6, 8]
for n in numbers:
if n % 2 != 0:
print(f"Found odd number: {n}")
break
else:
print("All numbers are even.")
# All numbers are even.
This pattern is useful for search loops where you want to handle the “not found” case cleanly.
Putting It Together
Here is a small program that combines conditionals and loops to categorize a list of numbers:
numbers = [15, -3, 0, 7, -8, 22, 0, -1, 4]
positive = 0
negative = 0
zeros = 0
for n in numbers:
if n > 0:
positive += 1
elif n < 0:
negative += 1
else:
zeros += 1
print(f"Positive: {positive}, Negative: {negative}, Zeros: {zeros}")
# Positive: 4, Negative: 3, Zeros: 2
Next Steps
With conditionals and loops mastered, you have the building blocks for writing real programs. From here, you can move on to functions, data structures, and file handling.