Control Flow: Loops
while loops, for loops, range(), break, continue β repeating actions efficiently.
- Write a
whileloop with a correct termination condition - Write a
forloop to iterate over a sequence - Use
range()with one, two, and three arguments - Use
breakto exit a loop andcontinueto skip an iteration - Use the accumulator pattern (sum, count, max, min)
- Write nested loops
while Loop
Keeps running as long as the condition is True. You must update the condition inside the loop or it runs forever.
# Count from 1 to 5
i = 1
while i <= 5:
print(i)
i += 1 # MUST update i, or infinite loop!
Use while when you don't know in advance how many iterations are needed.
for Loop
Iterates over a sequence (list, string, range) one item at a time.
# Print each item in a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Iterate over characters in a string
for ch in "hello":
print(ch)
range() Function
| Call | Produces |
|---|---|
range(5) | 0, 1, 2, 3, 4 (stop only) |
range(2, 8) | 2, 3, 4, 5, 6, 7 (start, stop) |
range(1, 10, 2) | 1, 3, 5, 7, 9 (start, stop, step) |
range(10, 0, -1) | 10, 9, 8, β¦ 1 (countdown) |
The stop value is exclusive β range(5) goes 0β4, not 0β5.
for i in range(1, 6):
print(i) # 1 2 3 4 5
break β Exit Loop Early
Immediately exits the loop, regardless of the condition.
for i in range(10):
if i == 5:
break # stops loop at i=5
print(i) # prints 0 1 2 3 4
continue β Skip an Iteration
Skips the rest of the current iteration and goes back to the loop condition.
for i in range(6):
if i % 2 == 0:
continue # skip even numbers
print(i) # prints 1 3 5
Accumulator Pattern
Initialise a variable before the loop, update it inside. Used for sum, count, max, min.
# Sum of 1 to 10
total = 0
for i in range(1, 11):
total += i
print("Sum:", total) # Sum: 55
# Count how many negatives
numbers = [3, -1, 7, -4, 2, -8]
count = 0
for n in numbers:
if n < 0:
count += 1
print("Negatives:", count) # 3
Nested Loops
A loop inside a loop. The inner loop runs completely for each iteration of the outer loop.
for i in range(1, 4): # outer
for j in range(1, 4): # inner
print(i, "*", j, "=", i*j)
# Total iterations = 3 Γ 3 = 9
while vs for β When to Use
| Use | When |
|---|---|
for | You know the number of iterations (iterate over sequence) |
while | You don't know how many times (wait for user input, search) |
Example 1 β Input validation with while
age = int(input("Enter age: "))
while age < 0 or age > 120:
print("Invalid. Try again.")
age = int(input("Enter age: "))
print("Valid age:", age)
Example 2 β Multiplication table
n = int(input("Which table? "))
for i in range(1, 11):
print(f"{n} x {i} = {n * i}")
Example 3 β Find first number divisible by 7 between 50β100
for i in range(50, 101):
if i % 7 == 0:
print("First:", i)
break
- Trace loop execution β know exactly what gets printed for a given loop.
- Know
range(start, stop, step): stop is exclusive, step can be negative. - Spot infinite loops β a
whileloop without updating the condition variable. - Accumulator pattern: initialise outside loop, update inside β very common in exams.
- Know when
breakexits immediately vscontinueskips to next iteration.
- Off-by-one errors:
range(1, 5)gives 1,2,3,4 β NOT 1,2,3,4,5. - Forgetting to update the loop variable in a
whileloop β infinite loop. - Wrong accumulator initialisation: sum starts at
0, product at1, max at first value. - Modifying a list while iterating over it β causes unexpected behaviour.
while cond:repeats while condition is True β update the variable!for x in seq:iterates over each item in a sequence.range(stop),range(start, stop),range(start, stop, step).break= exit loop;continue= skip to next iteration.- Accumulator: initialise before loop, update inside, use after.