1 / 32
Programming · Grade 10 · Chapter 8

Python: Loops

Letting the computer handle repetitive work — for loops, while loops, range(), and real-world iteration patterns.

Learning objectives

What We'll Cover

The problem

Writing the Same Line 100 Times

A student needs to print "Hello" 100 times. They start typing print("Hello") on each line. By line 10, they realise there must be a better way.

Discuss: What's the word we use in everyday language for "do this again and again"? Can you think of 3 repetitive tasks in technology that must be running on a loop right now?
The for loop

for Loops — Repeat a Known Number of Times

A for loop iterates over a sequence — running the indented block once for each item.

# Print Hello 5 times
for i in range(5):
    print("Hello")

# Print numbers 1 through 10
for i in range(1, 11):
    print(i)

# Count by 2
for i in range(0, 20, 2):
    print(i)
Understanding range()

range() — How It Works

range(start, stop, step) generates a sequence of numbers. The stop value is exclusive (not included).

range(5)                 # 0, 1, 2, 3, 4
range(1, 6)              # 1, 2, 3, 4, 5
range(0, 10, 2)          # 0, 2, 4, 6, 8
range(10, 0, -1)         # 10, 9, 8, ..., 1
Common mistake: range(1, 10) goes up to 9, not 10. If you want 10 included, use range(1, 11).
Quick check · 1

How many times does this loop run? for i in range(3, 9):

A9
B3
C6
D7
Click to reveal answer
Trace: i = 3, 4, 5, 6, 7, 8 — six values. stop=9 is not included. Formula: stop - start = 9 - 3 = 6.
Accumulating

Using Loops to Accumulate Values

One of the most important loop patterns: use a variable to accumulate a result across all iterations.

# Sum numbers 1 to 100
total = 0
for i in range(1, 101):
    total = total + i
print(f"Sum = {total}")  # 5050

# Count even numbers up to 20
count = 0
for i in range(1, 21):
    if i % 2 == 0:
        count += 1
print(f"Even count: {count}")
Iterating strings

for Loops Over Strings

A for loop can iterate over any sequence — including a string character by character.

word = "Python"

for letter in word:
    print(letter)

# Count vowels
vowels = 0
for ch in word:
    if ch.lower() in "aeiou":
        vowels += 1
print(f"Vowels: {vowels}")
The while loop

while Loops — Repeat While a Condition Is True

A while loop repeats as long as its condition remains True. Use it when you don't know in advance how many iterations are needed.

# Count down from 10
n = 10
while n > 0:
    print(n)
    n -= 1
print("Blast off!")

# Keep asking until valid input
age = -1
while age < 0:
    age = int(input("Enter a positive age: "))
Quick check · 2

When should you use a while loop instead of a for loop?

AWhen you know exactly how many times to repeat
BWhen you don't know how many repetitions are needed — only a condition to stop
CWhen the loop has to run at least once
Dwhile loops are always better than for loops
Click to reveal answer
Danger zone

Infinite Loops — The Most Common Bug

If a while loop's condition never becomes False, it runs forever, hanging your program.

❌ Infinite Loop
n = 10
while n > 0:
  print(n)
  # forgot: n -= 1

n stays 10 forever → crash
✅ Correct
n = 10
while n > 0:
  print(n)
  n -= 1  # ← essential

n decreases → eventually False
Rule: Every while loop must have something inside it that will eventually make the condition False.
Loop control

break and continue

# break: exit the loop immediately
for i in range(10):
    if i == 5:
        break  # stops at 5
    print(i)  # prints 0-4

# continue: skip this iteration, move to next
for i in range(10):
    if i % 2 == 0:
        continue  # skip evens
    print(i)  # prints 1,3,5,7,9
Quick check · 3

What does continue do inside a loop?

AStops the loop entirely
BSkips the rest of the current iteration and moves to the next one
CRestarts the loop from the beginning
DPauses until the user presses Enter
Click to reveal answer
Live coding · 1

Multiplication Table Generator

Write a program that prints the full multiplication table for a number entered by the user.

n = int(input("Multiplication table for: "))

for i in range(1, 13):
    result = n * i
    print(f"{n} × {i} = {result}")
Extension: Print tables for all numbers 1 to 12 using a nested loop.
Predict the output

Trace This Loop — What Does It Print?

total = 0
for i in range(1, 6):
    if i % 2 != 0:
        total += i
print(total)
Trace: i=1 (odd→+1), i=2 (skip), i=3 (odd→+3), i=4 (skip), i=5 (odd→+5). Total = 1+3+5 = 9.
Class activity: Trace row by row on the board.
Live coding · 2

Number Guessing Game

Build a while loop that keeps asking the user to guess a secret number.

secret = 42
guess = 0
attempts = 0

while guess != secret:
    guess = int(input("Guess: "))
    attempts += 1
    if guess < secret:
        print("Too low!")
    elif guess > secret:
        print("Too high!")
print(f"Got it in {attempts} attempts!")
Quick check · 4

What is the output of: for i in range(2, 10, 3): print(i)

A2, 3, 4, 5, 6, 7, 8, 9
B2, 5, 8
C2, 4, 6, 8
D3, 6, 9
Click to reveal answer
Trace: start=2, step=3 → 2, 5, 8, (11 ≥ stop=10 → stop)
Nested loops

Loops Inside Loops

A loop can contain another loop. The inner loop runs completely for each iteration of the outer loop.

# Times table grid (outer: rows, inner: columns)
for row in range(1, 6):
    for col in range(1, 6):
        print(f"{row * col:4}", end="")
    print()  # new line after each row
Time complexity note: Nested loops with size n each run n² times. A key concept in algorithm efficiency (Grade 11 Ch8).
Quick check · 5

How many times does the inner loop body run? for i in range(3): for j in range(4): print("x")

A3
B4
C7
D12
Click to reveal answer
Calculation: outer 3 iterations × inner 4 iterations = 3 × 4 = 12 total prints.
Challenge project

Password Strength Checker

Use a loop to analyse a password string and check for required character types.

password = input("Enter password: ")
has_upper = False
has_digit = False

for ch in password:
    if ch.isupper(): has_upper = True
    if ch.isdigit(): has_digit = True

if len(password) >= 8 and has_upper and has_digit:
    print("Strong password ✓")
else:
    print("Weak — needs 8+ chars, uppercase, digit")
Quick check · 6

What is wrong with this while loop? count = 0 — while count < 5: print(count)

AThe condition should use <=
Bcount should start at 1
Ccount is never incremented — this is an infinite loop
DNothing is wrong
Click to reveal answer
Fix: Add count += 1 inside the loop body so it eventually reaches 5 and the condition becomes False.
Loops in the real world

Where Are Loops Running Right Now?

Game Engine
The main game loop runs ~60 times per second: check input → update physics → render frame → repeat
Web Server
Listens in a while loop: while server is running: wait for request → process it → send response
AI Training
Iterates over the entire training dataset, sometimes thousands of times (called "epochs")
Streaming
A for loop reads audio/video chunks one by one and sends each to your screen in real time
Exit reflection

for vs. while — When Do You Choose?

For each scenario, discuss which loop type is most appropriate:

Before you go

Today We Learned...

Next chapter: Functions — organising code into reusable named blocks to avoid repetition and manage complexity.