Lesson 5 – While Loops (Iteration)
In this lesson you will:
- Explain what a while loop does (repetition / iteration).
- Use a condition to control how long a loop runs.
- Write while loops with correct indentation.
- Predict the output of simple loops.
- Use a loop to repeat input (e.g. "keep asking until valid") and do simple processing (count / total / max).
- Trace a while loop step by step and state the final output.
By the end you should be able to:
- Write a while loop to repeat code until a condition becomes False.
- Explain the difference between while and for loops (when to use each).
- Avoid common while loop mistakes (infinite loops, wrong condition, missing update, indentation errors).
- Trace a while loop and give the final output confidently.
1. Quick recap
From the previous lessons, remember:
- Variables store values.
- We can display output using
print(). - We can read input using
input()and convert toint()orfloat(). - Indentation matters: Python uses indentation to show which lines belong together.
ifstatements run code only when a condition isTrue.
Mini-check (predict):
What will this print?
for i in range(1, 5):
print(i)
2. What is a while loop?
A while loop lets Python repeat a block of code while a condition is True.
Useful phrase:
WHILE = "keep going while this is True"
It stops when the condition becomes False (this is the termination condition).
When should you use a while loop?
Use a while loop when you don't know how many times you need to repeat something:
- "Keep asking until the password is correct"
- "Keep entering numbers until the user types 0"
- "Keep asking until input is valid"
Use a for loop when you do know how many times:
- "Repeat 10 times"
- "Loop through a fixed range"
3. The while loop pattern (must know)
A while loop nearly always follows this pattern:
- Initialise the loop variable
- Condition (checked before each iteration)
- Body (repeated code)
- Update (change something so the loop can end)
Example:
i = 0 # 1) initialise
while i < 3: # 2) condition
print("Hi") # 3) body
i = i + 1 # 4) update
Key points:
- The condition is checked before every iteration
- If the condition is
Falseat the start, the loop runs 0 times - If nothing changes the condition, you may get an infinite loop
4. Example 1 – Counting up with a while loop
Predict first: What will the first number be? What will the last number be?
i = 1
while i <= 5:
print(i)
i = i + 1
What happens:
- Start
i = 1 - Check
i <= 5→True→ run the loop body - Increase
i - Repeat until
i <= 5becomesFalse
Try it yourself
Run it, then:
- Change it to print 1 to 10
- Change it to print 1 to 20
Output
Example Solution
# Print 1 to 10
i = 1
while i <= 10:
print(i)
i = i + 1
# Print 1 to 20
i = 1
while i <= 20:
print(i)
i = i + 1
5. Example 2 – Counting down
Predict first: Will it print 0?
i = 5
while i > 0:
print(i)
i = i - 1
print("Done")
Try it yourself
Make it count down from 10 to 1
Make it print "Blast off!" instead of "Done"
Output
Example Solution
# Count down from 10 to 1
i = 10
while i > 0:
print(i)
i = i - 1
print("Blast off!")
6. Example 3 – Step values (evens with while)
Predict first: How many numbers will print?
i = 2
while i <= 20:
print(i)
i = i + 2
Try it yourself
Print even numbers from 0 to 20
Print multiples of 3 up to 30
Output
Example Solution
# Even numbers from 0 to 20
i = 0
while i <= 20:
print(i)
i = i + 2
# Multiples of 3 up to 30
i = 3
while i <= 30:
print(i)
i = i + 3
7. Example 4 – Input validation (keep asking until valid)
Goal: keep asking until the user enters a number from 0 to 50.
Predict first: What happens if the user types -1? What happens if they type 25?
score = int(input("Enter a score (0 to 50): "))
while score < 0 or score > 50:
print("Invalid. Try again.")
score = int(input("Enter a score (0 to 50): "))
print("Accepted:", score)
What's happening here?
This is a common pattern called input validation. The code keeps asking for input until the user enters a valid value.
Step-by-step breakdown:
- First input (before the loop): We ask for a score once before checking the condition. This is important because we need a value to check!
- Check the condition:
while score < 0 or score > 50means "keep looping while the score is invalid" (too small OR too large). - If invalid: Print an error message and ask again inside the loop.
- If valid: The condition becomes
False, the loop stops, and we print "Accepted".
Example scenario:
- User types
-1→ Invalid (too small) → Loop runs → Ask again - User types
100→ Invalid (too large) → Loop runs → Ask again - User types
25→ Valid (between 0 and 50) → Loop stops → Print "Accepted: 25"
Why ask before the loop AND inside the loop?
- We ask before the loop to get the first value to check.
- We ask inside the loop to get a new value if the first one was invalid.
- If we only asked inside the loop, we'd need to set
scoreto an invalid value first (which is messy).
Try it yourself
Change it to accept 1 to 10 instead.
Output
Example Solution
score = int(input("Enter a score (1 to 10): "))
while score < 1 or score > 10:
print("Invalid. Try again.")
score = int(input("Enter a score (1 to 10): "))
print("Accepted:", score)
8. Sentinel loops (repeat until a stop value)
A sentinel is a special value that means "stop" (e.g. 0 or -1).
Example – Running total until 0
Predict first: What if the first number entered is 0?
total = 0
num = int(input("Enter a number (0 to stop): "))
while num != 0:
total = total + num
num = int(input("Enter a number (0 to stop): "))
print("Total =", total)
Try it yourself
Add a count variable and print how many numbers were entered
Calculate the average (only if count > 0)
Output
Example Solution
total = 0
count = 0
num = int(input("Enter a number (0 to stop): "))
while num != 0:
total = total + num
count = count + 1
num = int(input("Enter a number (0 to stop): "))
if count > 0:
average = total / count
print("Total =", total)
print("Count =", count)
print("Average =", average)
else:
print("No numbers entered")
9. Guessing game pattern (classic while loop)
Example 1 – Basic guessing loop
Predict first: What happens if the first guess is correct?
This is a classic guessing game pattern.
Goal:
- generate a random number
- loop while
guess != secret - ask for input inside the loop
import random
secret = random.randint(1, 10)
guess = int(input("Guess a number (1 to 10): "))
while guess != secret:
guess = int(input("Wrong! Guess again (1 to 10): "))
print("Correct!")
Video
Video: Building a guessing game step-by-step
The video should show:
- setting up secret
- getting the first guess before the loop
- using while guess != secret
- re-input inside the loop
- testing with a few guesses
Video: Building a guessing game step-by-step
Output
Example Solution
import random
secret = random.randint(1, 20)
guess = int(input("Guess a number (1 to 20): "))
while guess != secret:
guess = int(input("Nope! Try again (1 to 20): "))
print("Correct!")
10. Indentation and loop blocks (important)
A while loop line ends with a colon :. The code inside the loop must be indented.
Example – one line inside the loop:
i = 0
while i < 3:
print(i)
i = i + 1
Example – two lines inside the loop:
i = 0
while i < 3:
print("Number:", i)
print("-----")
i = i + 1
print("Done")
What happens:
- The indented lines repeat
print("Done")runs once at the end
Try it yourself
Move i = i + 1 back to the left. Predict what changes, then run it.
Output
Example Solution
When i = i + 1 is not indented, it's outside the loop. This means i never changes inside the loop, so the condition i < 3 stays True forever → infinite loop!
# Correct version:
i = 0
while i < 3:
print("Number:", i)
print("-----")
i = i + 1 # Must be indented!
print("Done")
11. Common misconceptions (very common in tests)
Mistake 1: Thinking the condition is checked only once
Wrong idea: "It checks at the start, then just repeats."
Fix: It checks before every iteration.
Mistake 2: Using the wrong condition direction
Wrong:
while guess == secret:
...
Correct:
while guess != secret:
...
Mistake 3: Forgetting to update the loop variable
Wrong (infinite loop risk):
i = 0
while i < 5:
print(i)
Correct:
i = 0
while i < 5:
print(i)
i = i + 1
Mistake 4: Update line is outside the loop (indentation error)
If i = i + 1 is not indented, i never changes inside the loop.
Mistake 5: Expecting the loop to run at least once
A while loop can run 0 times if the condition is False at the start.
Mistake 6: Confusing validation with a single if
Validation usually needs a loop: keep asking until valid.
Mistake 7: Confusing sentinel and counter loops
Sentinel = special value ends input (e.g. -1 to stop).
Counter = repeats a number of times (e.g. 10 guesses max).
Mistake 8: Off-by-one boundaries
Be careful with < vs <=. Trace the last iteration to check.
13. Understanding Quiz
Answer all questions below, then click "Check Answers" at the end to see your score.
i = 0
while i < 3:
print(i)
i = i + 1
i = 0
while i < 5:
print(i)
x = 10
while x > 0:
x = x - 4
print(x)
guess = int(input())
while guess == secret:
guess = int(input())
print("Correct")
They want to keep asking until the guess is correct. What should they change?
score = int(input())
while score < 0 or score > 50:
score = int(input())
12. Coding tasks – While loops practice
Complete all the tasks below. Do one task at a time, run your code, and check the output.
-
Task 1 – Count to 10
Print the numbers 1 to 10 using a while loop. -
Task 2 – Even numbers to 20
Print the even numbers from 2 to 20 using a while loop. -
Task 3 – Input validation (1 to 10)
Keep asking for a number until the user enters a number from 1 to 10. Then print "Thanks". -
Task 4 – Guessing game (basic)
Make the simple guessing game: generate a random number (1 to 10), loop whileguess != secret, and ask for guesses until correct. -
Task 5 – Guessing game extension (too high/too low + counter)
Continue from Task 4: Add feedback ("Too high" / "Too low") and a counter for guesses. -
Task 6 – Guessing game extension (limited guesses)
Continue from Task 5: Add limited guesses: player has 5 tries; if they fail, print "Out of guesses" and reveal the number. -
Task 7 – Guessing game extension (replay loop)
Continue from Task 6: After a game ends, ask "Play again? (y/n)" and repeat the whole game while the answer is "y". -
Task 8 – Running total until sentinel
A shopkeeper enters sales amounts throughout the day. Ask for sales amounts until the user enters 0 (to stop). Print the total sales for the day. If no sales were entered (first input is 0), print "No sales today".
Answer all the above tasks here
Use the editor below to complete the coding tasks above.