while loops
🌍 In real life. You fill a bucket with a mug: pour a mug, look at the bucket, and if it isn't full yet, pour another. You don't decide in advance how many mugs it takes; you check before every mug and stop as soon as it's full.
That "check, do, check again" pattern is a loop, and while is Python's way to write it.
The idea in one sentence: while repeats its block as long as its condition is True, checking the condition again before every lap.
Its words:
- loop: code that runs again and again
- lap (or iteration): one run through the loop's block
- loop variable: the variable the condition depends on, which the block changes
- infinite loop: a loop whose condition never becomes False, so it never stops
Step by step, for while count <= 3: with count starting at 1:
- Check:
1 <= 3is True, so run the block: print 1, thencountbecomes 2. - Back to the top. Check
2 <= 3: True, so print 2;countbecomes 3. - Check
3 <= 3: True, so print 3;countbecomes 4. - Check
4 <= 3: False, so the loop ends, and Python carries on below it.
count = 1
while count <= 3:
print(count)
count += 1
print("Done!")How Python does it. The condition is checked only at the top of each lap, never in the middle of the block. So the block always finishes its lap, even if the condition became False halfway through. If the condition is False the very first time, the block never runs at all.
Something inside the block must change the loop variable; otherwise the condition never becomes False. A loop can also count down:
n = int(input("Start from: "))
while n > 0:
print(n)
n -= 1
print("Liftoff!")while is the right loop when you don't know in advance how many laps you need, like doubling a number until it gets big enough:
money = 1
days = 0
while money < 100:
money = money * 2
days += 1
print(days, "days to reach", money)What it costs. A loop's block runs once per lap, so the number of laps is the work. Counting from 1 up to n takes n laps: a million laps for n = 1,000,000. The doubling loop above is far quicker: money goes 1, 2, 4, 8, … and passes 100 after only 7 laps. To pass a million it would need just 20 laps, because each lap doubles it.
Mistakes and edge cases.
- Forgetting to change the variable. Without
count += 1,count <= 3stays True forever: an infinite loop. Press ⏹ Stop to end it. - The change outside the block.
count += 1written without its indent runs only after the loop, so the loop never ends. - < or <=.
while count < 3:runs 2 laps from 1, not 3. Check the last lap by hand. - A loop that never starts. If the condition is False at the start, the block is skipped and there's no error.
- The variable doesn't exist yet.
while count <= 3:beforecount = 1givesNameError: name 'count' is not defined.
Quiz
What does this print?
n = 3 while n > 0: print(n) n -= 1What does this print?
x = 1 while x < 20: x = x * 2 print(x)What does this print?
i = 5 while i < 3: print("hi") print("end")What happens if you forget
count += 1in awhile count <= 3:loop?- The loop never stops, because count stays the same
- Python adds 1 for you
- The loop runs exactly 3 times
Which line has a mistake?
count = 0 while count < 3 print(count) count += 1
Coding tasks
Ask for a whole number
n. Print the numbers from 1 ton, one per line.Ask for a whole number. Count down from it to 1, one number per line, then print
Go!. If the number is 0, just printGo!.Ask for a whole number
n(1 or more). Start with 1 and keep doubling it while it is smaller thann. Print the number you end up with: the first of 1, 2, 4, 8, 16, … that is at leastn.