07 Apr 2026
Control Flow: Conditionals and Loops
If-else decisions, while loops, for loops, ranges, and repeated calculations in Python.
A program is not always a straight list of instructions. Sometimes it must choose between alternatives, and sometimes it must repeat a calculation many times. Control flow decides which statements run and how many times they run.
The two basic ideas are decision and repetition. Conditionals handle decisions. Loops handle repetition.
Conditionals
A conditional executes code only when a condition is true.
energy = -13.6
if energy < 0:
print("bound state")
else:
print("unbound state")
Use elif when several cases are possible.
temperature = 300
if temperature < 273:
print("below freezing")
elif temperature == 273:
print("freezing point")
else:
print("above freezing")
While loops
A while loop repeats while a condition remains true.
n = 1
while n <= 5:
print(n)
n = n + 1
The update step is important. Without it, the loop may never stop.
A while loop is natural when the stopping condition is based on convergence, such as repeating an iteration until the change becomes smaller than a chosen tolerance.
For loops
A for loop is useful when the number of repetitions is known.
for n in range(1, 6):
print(n)
The command range(1, 6) gives 1, 2, 3, 4, 5.
A for loop is also useful for processing each value in a list of readings.
Looping over data
measurements = [1.2, 1.4, 1.3, 1.5]
total = 0.0
for value in measurements:
total = total + value
average = total / len(measurements)
print(average)
This is a typical pattern: initialize, loop, update, and then use the final result.
Nested control flow
Conditionals can be placed inside loops.
for n in range(1, 11):
if n % 2 == 0:
print(n, "even")
else:
print(n, "odd")
Table of values
Print a table of $x$ and $x^2$ from $x=1$ to $x=5$.
for x in range(1, 6):
print(x, x**2)
The output is
1 1
2 4
3 9
4 16
5 25
This is a standard use of a for loop: the number of repetitions is known in advance.
Conditional example
Classify a number as positive, negative, or zero.
x = -4
if x > 0:
print("positive")
elif x < 0:
print("negative")
else:
print("zero")
The order of the tests matters. Python checks the conditions from top to bottom and runs the first matching block.
Key points
- Use
if,elif, andelsefor decisions. - Use
whilewhen repetition depends on a condition. - Use
forwhen processing a known sequence. - Keep loop bodies small and readable.
Practice questions
- Write an
if-elseprogram to test whether a number is positive or negative. - Distinguish between
whileandforloops. - Write a loop to print $x$ and $x^2$ for $x=1$ to $5$.
- Find the average of values stored in a list using a loop.
- Why must a
whileloop contain a proper update step?
Discussion