Python Loops
Master for loops, while loops, range(), break/continue statements, and nested loops in Python.
for Loops
A for loop repeats a block of code for each item in a sequence (like a list, string, or range). It is used when you know how many times you want to loop.
# Loop through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}")
# Loop with range()
for i in range(5): # 0, 1, 2, 3, 4
print(f"Count: {i}")
for i in range(2, 10, 2): # 2, 4, 6, 8 (start, stop, step)
print(f"Even: {i}")
# Loop through a string
for char in "Python":
print(char, end=" ") # P y t h o n
while Loops
A while loop repeats a block of code as long as a condition remains True. Be careful to ensure the condition eventually becomes False, or the loop will run forever (an infinite loop).
# Count down from 5
count = 5
while count > 0:
print(f"Countdown: {count}")
count -= 1 # Same as count = count - 1
print("Blast off!")
# Accumulator pattern
total = 0
number = 1
while number <= 100:
total += number # Add each number to total
number += 1
print(f"Sum of 1 to 100 = {total}")
break, continue, and Nested Loops
break exits the loop immediately. continue skips the rest of the current iteration and moves to the next. Nested loops are loops inside loops.
# break - exit early when we find what we need
names = ["Alice", "Bob", "Charlie", "Diana"]
for name in names:
if name == "Charlie":
print(f"Found {name}!")
break
print(f"Checking {name}...")
# continue - skip odd numbers
for i in range(1, 11):
if i % 2 != 0:
continue # Skip odd numbers
print(f"Even: {i}") # Only prints 2, 4, 6, 8, 10
# Nested loops - multiplication table
for row in range(1, 4):
for col in range(1, 4):
print(f"{row}x{col}={row*col}", end="\t")
print() # New line after each row
Key Vocabulary
Iteration
One complete execution of the loop body. A loop with 5 items has 5 iterations.
range()
A function that generates a sequence of numbers: range(start, stop, step).
Infinite Loop
A loop that never stops because its condition never becomes False.
Accumulator
A variable that builds up a result across iterations, like summing numbers.
Worked Examples
Calculate the average of student scores using a for loop
scores = [85, 92, 78, 95, 88, 76, 90]
total = 0
for score in scores:
total += score
average = total / len(scores)
print(f"Total: {total}")
print(f"Average: {average:.1f}")
Step 1: We initialise total = 0 as an accumulator.
Step 2: Each iteration adds the current score to total.
Output: Total: 604 | Average: 86.3
Use a while loop to guess a number
secret = 7
guess = 0
attempts = 0
while guess != secret:
guess = int(input("Guess the number (1-10): "))
attempts += 1
if guess < secret:
print("Too low!")
elif guess > secret:
print("Too high!")
print(f"Correct! You got it in {attempts} attempts.")
Step 1: The while loop continues until the guess matches the secret number.
Step 2: We track attempts and give hints (too low/high) each round.
Print a times table using nested loops
# Print multiplication table for 1-5
for i in range(1, 6):
for j in range(1, 6):
result = i * j
print(f"{result:4}", end="")
print() # New line after each row
Step 1: The outer loop controls the row (1 to 5).
Step 2: The inner loop controls the column (1 to 5). {result:4} pads the number to 4 characters.
Output: A 5x5 multiplication table grid.
Knowledge Check
Select the correct answer for each question. Click "Check Answer" to see if you are right.
Question 1
How many times does for i in range(3): print(i) print?
Question 2
What does break do inside a loop?
Question 3
What values does range(1, 6) generate?
Question 4
Which loop type is best when you do NOT know how many times to repeat?
Question 5
What does continue do inside a loop?
Key Concepts Summary
- ● for loops iterate over sequences (lists, strings, range). Best when you know the number of iterations.
- ● while loops repeat while a condition is True. Best for unknown iteration counts.
-
●
range(start, stop, step)generates sequences of numbers. -
●
breakexits a loop;continueskips to the next iteration. - ● Nested loops place one loop inside another, useful for grids and tables.