while loops · Python from Zero
How do you loop until something happens, when you can't know the count in advance?
Course contentsWhy you need it
"Keep asking for numbers until the user types 0." "Double the money until it passes 1000." You don't know how many rounds that takes. The robot used while not at_goal(); now you'll write conditions with variables.
The intuition
A while loop has three parts. If any is missing you get a bug:
- Set up the variable the condition uses.
- Check the condition at the top of each round.
- Change the variable inside the body, so the condition can eventually become False.
money = 100 # 1. set up
years = 0
while money < 1000: # 2. check
money = money * 2 # 3. change
years = years + 1
print(years)Reading input until a stop value is a classic pattern: read once before the loop, then read again at the end of every round.
Definition
Loop condition
The loop condition of a while loop is evaluated before each iteration; the loop stops when it becomes False.
Sentinel value
A sentinel value is a special input, such as 0, that signals the end of the data.
Examples
Doubling
Try it yourselfHow many doublings until 100 passes 1000?
money = 100
years = 0
while money < 1000:
money = money * 2
years = years + 1
print(years, money)- L3100 < 1000: True, enter the loop.
money = 100 - L4Double: 200. years = 1.
money = 200, years = 1 - L4400 (2), 800 (3), 1600 (4)...
money = 1600, years = 4 - L31600 < 1000: False, the loop ends.
- L6Print once after the loop.
4 1600
Sum until 0
Try it yourselfEdit the Input box: any numbers, ending with 0.
total = 0
n = int(input())
while n != 0:
total = total + n
n = int(input())
print(total)5 8 2 0
- L2Read the first number before the loop.
n = 5 - L35 != 0, so add it.
total = 5 - L5Read the next number at the end of the round.
n = 8 - L3...when 0 is read the condition is False and the loop stops.
total = 15
Common mistakes
Forgetting to change the variable
Without n = int(input()) at the end of the body, n never changes and the loop never ends. This site stops it after a few seconds.
for or while?
Know the number of rounds (or have a sequence)? Use for. Waiting for a condition? Use while.
Quick quiz
1. What does this print?
n = 1
while n < 20:
n = n * 3
print(n)Show the answer
Answer: A
1 → 3 → 9 → 27. 27 < 20 is False, so the loop stops at 27.
2. What does this print?
i = 5
while i > 0:
i = i - 2
print(i)Show the answer
Answer: A
5 → 3 → 1 → -1. The check happens only at the top of each round.
Practice
3 exercises in three steps: predict what a program prints, change a program to meet a new requirement, then write one from scratch. Your code runs in the browser and is checked the moment you submit.
- PredictHalving
Type exactly what this program prints.
- ModifyAlso count them
The program adds numbers until 0. Also print, on a second line, how many numbers were added (not counting the 0).
- WriteCollatz steps
Read a positive whole number n. Repeat until n is 1: if n is even, n becomes n // 2; otherwise n becomes 3 × n + 1. Print how many steps it took. (For 6: 6 → 3 → 10 → 5 → 16 → 8 → 4 → 2 → 1 is 8 steps.)
Practise this lesson
Open the interactive lesson to edit and run these examples and solve the exercises with instant feedback. Free to start, no sign-up.
Interactive lessons open in order. If you have not done the earlier ones yet, you start at the course map.
Terms in this lesson
| Term | Chinese | Definition |
|---|---|---|
| Loop condition | 循环条件 | The expression a while loop checks before each round. |
| Sentinel value | 结束标记 | A special input value that marks the end of the data. |
| Counter | 计数器 | A variable that is increased by 1 each time something happens. |