Chapter 4

Loops

FREE For Loops โ€” Repeating with Style
Article ยท 15 min
๐Ÿ“ Homework 13

Imagine you need to print "Hello" 100 times. Would you write 100 print() statements? Of course not! That's what for loops are for โ€” they let you repeat code a specific number of times.


๐Ÿ” The Basic for Loop with range()

Syntax:

for variable in range(count):
    # code to repeat

Example โ€” repeat 5 times:

for i in range(5):
    print("Hello!")

Output:

Hello!
Hello!
Hello!
Hello!
Hello!
๐Ÿ”‘ How it works: range(5) generates the numbers 0, 1, 2, 3, 4. The loop runs once for each number. The variable i takes each value in turn.

Example โ€” print the loop variable:

for i in range(5):
    print(f"Iteration {i}")

Output:

Iteration 0
Iteration 1
Iteration 2
Iteration 3
Iteration 4
1
Practice 1
โœ๏ธ Try it yourself!
1 Code
Write a for loop that prints "Python is fun!" 8 times.
2 Code
Write a for loop that prints the numbers 0 to 9.

๐ŸŽฏ Customising range(start, stop, step)

Syntax:

range(start, stop)     # from start to stop-1
range(start, stop, step)  # with custom step

Example โ€” start at 1, stop before 6:

for i in range(1, 6):
    print(i, end=" ")   # 1 2 3 4 5

Example โ€” count by 2s:

for i in range(2, 11, 2):
    print(i, end=" ")   # 2 4 6 8 10

Example โ€” count down:

for i in range(10, 0, -1):
    print(i, end=" ")   # 10 9 8 ... 1

print("๐Ÿš€ Blast off!")
๐Ÿ”‘ Remember: range(start, stop, step) stops before reaching stop. So range(1, 6) gives 1,2,3,4,5 (not 6).
2
Practice 2
โœ๏ธ Try it yourself!
1 Code
Print the 3 times table: 3, 6, 9, 12, ... up to 30.
2 Code
Print the numbers from 20 down to 0, stepping by 2.
3 Code
Print all odd numbers between 1 and 19.

๐Ÿ“‹ Looping Through a List

Syntax โ€” for-each style:

for item in list:
    print(item)

Example:

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(f"I love {fruit}s!")

Output:

I love apples!
I love bananas!
I love cherries!

Using index โ€” range(len()):

numbers = [10, 20, 30, 40]
for i in range(len(numbers)):
    print(f"Index {i}: {numbers[i]}")
3
Practice 3
โœ๏ธ Try it yourself!
1 Code
Create a list of 4 colours and print each one with a message like "My favourite colour is blue".
2 Code
Given nums = [5, 10, 15, 20], write a loop that prints each number doubled (10, 20, 30, 40).

๐Ÿ”ข enumerate() โ€” Index and Value Together

students = ["Alice", "Bob", "Charlie"]
for i, name in enumerate(students):
    print(f"Student {i+1}: {name}")

Output:

Student 1: Alice
Student 2: Bob
Student 3: Charlie
4
Practice 4
โœ๏ธ Try it yourself!
1 Code
Use enumerate() to print a shopping list with numbered items.

๐Ÿ›‘ break and continue

break โ€” exit the loop immediately:

for i in range(10):
    if i == 5:
        break       # stop when i reaches 5
    print(i, end=" ")   # 0 1 2 3 4

continue โ€” skip to the next iteration:

for i in range(10):
    if i % 2 == 0:
        continue    # skip even numbers
    print(i, end=" ")   # 1 3 5 7 9
5
Practice 5
โœ๏ธ Try it yourself!
1 Code
Print numbers from 1 to 20, but stop when you reach 13 (use break).
2 Code
Print numbers from 1 to 15, but skip multiples of 3 (use continue).

๐Ÿงฎ Algorithms with For Loops โ€” Totalling and Counting

Now that you understand the basic for loop, let's look at two essential exam patterns.

Totalling โ€” add up values:

total = 0
for score in [45, 78, 92, 60, 55]:
    total = total + score   # or total += score
print(f"Total: {total}")    # 330

Counting โ€” count how many match a condition:

count = 0
for score in [45, 78, 92, 60, 55]:
    if score >= 50:
        count = count + 1   # or count += 1
print(f"Passed: {count}")   # 4
๐Ÿ”‘ Key Pattern: Always initialise your total/counter to 0 before the loop. Update it inside the loop.

Combined โ€” find average:

scores = [45, 78, 92, 60, 55]
total = 0
count = 0

for s in scores:
    total += s
    count += 1

average = total / count
print(f"Average: {average:.1f}")  # 66.0
6
Practice 6
โœ๏ธ Try it yourself!
1 Code
Use a for loop to calculate the sum of all numbers from 1 to 50.
2 Code
Count how many numbers in the list [12, 7, 9, 15, 4, 20, 3] are greater than 10.
3 Code
Calculate the average of the numbers [8, 12, 15, 9, 11].

๐Ÿ”„ REPEAT...UNTIL (Post-condition Loop)

IGCSE pseudocode has a loop that always runs at least once. In Python, we use while True + break:

# Pseudocode equivalent:
# REPEAT
#     OUTPUT "Enter a positive number:"
#     INPUT num
# UNTIL num > 0

while True:
    num = int(input("Enter a positive number: "))
    if num > 0:
        break
    print("Try again!")
7
Practice 7
โœ๏ธ Try it yourself!
1 Code
Write a loop that keeps asking for a password until the user enters "python123".
FREE While Loops โ€” Keep Going Until...
Article ยท 15 min
๐Ÿ“ Homework 12

A while loop keeps running as long as a condition is True. Unlike for (which runs a fixed number of times), while is perfect when you don't know how many iterations you'll need.


๐Ÿ”„ The Basic while Loop

Syntax:

while condition:
    # code to repeat

Example โ€” count to 5:

count = 0
while count < 5:
    print(f"Count is {count}")
    count = count + 1   # ๐Ÿ”‘ Don't forget to update!

Output:

Count is 0
Count is 1
Count is 2
Count is 3
Count is 4
โš ๏ธ Infinite Loop Warning! Always make sure the condition eventually becomes False. If you forget count += 1, the loop runs forever! Press Ctrl+C to stop an infinite loop.
1
Practice 1
โœ๏ธ Try it yourself!
1 Code
Write a while loop that prints numbers from 10 down to 1.
2 Code
Write a while loop that prints "Keep going!" 5 times.

๐Ÿง  Using while with User Input

A very common use โ€” keep asking until the user gives valid input.

num = 0
while num <= 0:
    num = int(input("Enter a positive number: "))
    if num <= 0:
        print("That's not positive! Try again.")

print(f"Thanks! You entered {num}")
2
Practice 2
โœ๏ธ Try it yourself!
1 Code
Write a while loop that keeps asking "Are we there yet?" until the user types "yes".
2 Code
Write a loop that asks for a password until the user enters "secret123".

๐ŸŽฏ while vs for โ€” When to Use Which

Use forUse while
You know the number of iterationsYou're waiting for a condition
Looping through a list/rangeReading input until valid
Counting or iteratingNumber guessing, game loops
3
Practice 3
โœ๏ธ Try it yourself!
1 Code
Describe a situation where a while loop is better than a for loop.

๐Ÿ›‘ Using break to Exit a While Loop

while True:
    cmd = input("Enter command ('quit' to exit): ")
    if cmd == "quit":
        break
    print(f"Executing: {cmd}")

while True creates an infinite loop โ€” but break lets you exit from inside.

4
Practice 4
โœ๏ธ Try it yourself!
1 Code
Write a calculator loop that keeps asking for two numbers and an operator, and shows the result. Stop when the user types "quit".

๐Ÿงฎ Algorithms with While Loops โ€” Totalling with Unknown Count

Now that you understand the basic while loop, here's the key exam pattern:

# Enter scores until -1, then show average
total = 0
count = 0
score = int(input("Enter score (-1 to stop): "))

while score != -1:
    total += score
    count += 1
    score = int(input("Enter score (-1 to stop): "))

if count > 0:
    print(f"Total: {total}")
    print(f"Average: {total/count:.1f}")
else:
    print("No scores entered.")

Finding the first match:

# Find the first number divisible by 7
num = 1
while num % 7 != 0:
    num += 1
print(f"The first multiple of 7 is {num}")  # 7
5
Practice 5
โœ๏ธ Try it yourself!
1 Code
Use a while loop to keep entering numbers until the user types 0, then print the total.
2 Code
Use a while loop to find the smallest number whose square is greater than 1000.
3 Code
Use a while loop to reverse a number (e.g., 12345 โ†’ 54321).
4 Code
Use a while loop to print the Fibonacci sequence up to 1000.