Python while loops
- 1How a while loop runs, Learn
- 2Shortcuts and break, Learn
- 3Run it: a countdown and doubling, Try
- 4Count by threes, Practice
- 5Guess the password, Practice
- 6Halving until one, Practice
- 7The loop that never runs, Break/fix
- 8Add up until done, Practice
- 9Skip the empty scans, Practice
- 10Level up from XP, Your turn
Builds on lessons 1 to 7. Start at lesson 1
Learn
How a while loop runs
A while loop repeats a block as long as its condition is true.
count = 3
while count > 0
print(count)
count = count - 1
endwhile
print("Liftoff!")count ← 3
WHILE count > 0
OUTPUT count
count ← count - 1
ENDWHILE
OUTPUT "Liftoff!"count = 3
while count > 0:
print(count)
count = count - 1
print("Liftoff!")Here is exactly what happens: Python checks count > 0. True, so it runs the indented block, then jumps back up and checks again. When the condition finally comes out false, it skips the block and carries on with the line after the loop. The condition is only checked at the top of each round, not halfway through.
The block must change something that the condition depends on. Delete the line count = count - 1 and count stays 3 forever, so the condition never becomes false. That is an infinite loop, and your program will hang until you stop it. Everyone writes one eventually; consider it a rite of passage.
Learn
Shortcuts and break
A shortcut you will see everywhere: count -= 1 means count = count - 1. Same for +=, *= and friends.
Sometimes you do not know in advance when to stop. Then you can write while True: (a loop that would run forever) and use break to jump out from inside:
while True:
guess = input()
if guess == "42":
breakwhile is the right tool when you are repeating "until something happens": until the user types the right password, until a number gets small enough, until the game is over. When you know how many times to repeat, or you are going through a collection of things, the for loop in the next lesson is usually cleaner.
GCSE exam boards
- OCR 2.2.1 Programming fundamentals
- AQA 3.2.2 Sequence, selection, iteration
- Edexcel 6.2.2 Selection and repetition
Try
Run it: a countdown and doubling
The example is already in the editor. Run it, change one thing, and run it again.
In exam pseudocode
count = 3
while count > 0
print(count)
count = count - 1
endwhile
print("Liftoff!")
n = 1
steps = 0
while n <= 1000
n = n * 2
steps = steps + 1
endwhile
print(str(steps) + " doublings gives " + str(n))count ← 3
WHILE count > 0
OUTPUT count
count ← count - 1
ENDWHILE
OUTPUT "Liftoff!"
n ← 1
steps ← 0
WHILE n ≤ 1000
n ← n * 2
steps ← steps + 1
ENDWHILE
OUTPUT INT_TO_STRING(steps) + " doublings gives " + INT_TO_STRING(n)count = 3
while count > 0:
print(count)
count -= 1
print("Liftoff!")
# How many times can we double 1 before passing 1000?
n = 1
steps = 0
while n <= 1000:
n *= 2
steps += 1
print(f"{steps} doublings gives {n}")count = 3
while count > 0:
print(count)
count -= 1
print("Liftoff!")
# How many times can we double 1 before passing 1000?
n = 1
steps = 0
while n <= 1000:
n *= 2
steps += 1
print(f"{steps} doublings gives {n}")
Practice
Count by threes
Use a while loop to print the numbers 3, 6, 9, 12 and 15, each on its own line.
Constraint
- Work it out with code. Printing the answer as text doesn't count.
n = 3
while n <= 15:
print(n)
n += 1
Practice
Guess the password
Keep reading lines with input() until someone types open sesame. For every wrong guess print Nope. When the right guess arrives, print Welcome in and stop. With the given input, the output is two Nope lines then Welcome in.
Your program reads the Input box under the editor.
guess = input()
print("Welcome in")
PracticePredict the output
Halving until one
Type exactly what this prints. Track n on paper, one round at a time.
n = 10
while n > 1:
n = n // 2
print(n)
Break/fixFix the bug
The loop that never runs
The player starts with 3 lives and should see each one counted down before Game over. Instead the program goes straight to Game over.
Constraint
- Work it out with code. Printing the answer as text doesn't count.
lives = 3
while lives == 0:
print("Lives left:", lives)
lives -= 1
print("Game over")
Practice
Add up until done
Read numbers, one per line, until someone types done. Then print the total and how many numbers there were, exactly like the examples. If done comes first, both are 0.
Milestones
- Three numbers
- Nothing typed
- One number
Your program reads the Input box under the editor. Check also tries 2 other inputs.
total = 0 items = 0
Practice
Skip the empty scans
break leaves a loop. Its partner is continue: it skips the rest of the block for this round only and jumps back to the top of the loop, where the condition is checked again.
while True:
line = input().strip()
if line == "":
continue # nothing to do with an empty line: next round
print("Got", line)A ticket scanner at a gig sends one code per line until it sends close. Sometimes it sends an empty line (or one with only spaces) by mistake. Print Scanned: and the code for every real code, skip the empty lines with continue, then print how many tickets were scanned.
Constraint
- Use continue to skip the empty lines.
Milestones
- Two empty lines
- Nothing scanned
Your program reads the Input box under the editor. Check also tries 1 other inputs.
count = 0
while True:
code = input().strip()
if code == "close":
break
print("Scanned:", code)
count += 1
print("Tickets:", count)
Your turn
Level up from XP
In a game, going from level 1 to level 2 costs 100 XP, and each level after that costs double the one before: 200 XP to reach level 3, 400 to reach level 4, and so on. Read a player's total XP (a whole number). Spend it on levels for as long as there is enough, then print the level they reached and how much more XP the next level needs, like the examples.
Milestones
- 350 XP
- A brand new player
- Exactly one level
- Exactly four levels
- One short
On your own. Hints open after your first check.
Your program reads the Input box under the editor. Check also tries 4 other inputs.
Passed
You can now
Save your progress to a free account
Next up: Core
Loops, logic, lists, functions, dictionaries, tuples and sets, with a checkpoint after each group so you know it stuck.
- 08Python while loops
- 09Python for loops and range()
- 10Booleans in Python: and, or, not
- 11Python checkpoint: loops and logic
- 12Python lists
- 13Python list methods: split, join and more
- 14Python functions: return and print
- 15Python function parameters and scope
- 16Python checkpoint: lists and functions
- 17Python dictionaries
- 18Python tuples and sets
- 19Python checkpoint: collections