Control flow in Python – if/else statements for making decisions, and for/while loops for repeating work.
If-else statements: making decisions
An if statement runs code only when a condition is true. Otherwise Python skips it or runs the else block instead:
age = 20
if age >= 18:
print("You are an adult.")
else:
print("You are not an adult.")
Checks whether age is 18 or over and prints the matching message.
Elif: adding more conditions
When you need more than two paths, use elif (short for else if). Python checks each condition in order and runs the first one that matches:
temperature = 15
if temperature > 30:
print("It's a hot day.")
elif temperature > 20:
print("It's a nice day.")
else:
print("It's cold.")
Prints a message based on which temperature range applies.
Loops: repeating tasks
Writing the same code ten times is tedious. Loops run a block repeatedly. Python has two: for and while.
- For loop: iterates over a sequence – a list, tuple, string, or
range. Use it when you know how many times you want to loop.
for i in range(5):
print(i)
Prints 0 through 4. range(5) generates numbers from 0 up to (but not including) 5.
- While loop: keeps going as long as a condition is true. Use it when you do not know the count upfront.
count = 0
while count < 5:
print(count)
count += 1
Also prints 0 through 4. The loop stops when count reaches 5.
Breaking out of loops
break exits a loop early:
for i in range(10):
if i == 5:
break
print(i)
Prints 0 through 4, then stops when i hits 5.
Continuing a loop
continue skips the rest of the current iteration and moves to the next:
for i in range(10):
if i % 2 == 0:
continue
print(i)
Prints only the odd numbers between 0 and 9.
Nested loops
A loop inside another loop. Handy for grids, tables, or any two-dimensional data:
for i in range(3):
for j in range(3):
print(f"({i}, {j})")
Prints coordinate pairs for a 3×3 grid.
Decisions and loops are what make programs useful rather than just a straight line of instructions. Try modifying the examples – change the conditions, adjust the ranges, see what breaks.

