Everyone Can Learn Program
中文 Start learning
Course 2 · Python BasicsLesson 10 of 14Free to read

while loops · Python from Zero

How do you loop until something happens, when you can't know the count in advance?

Course contents

Why 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:

  1. Set up the variable the condition uses.
  2. Check the condition at the top of each round.
  3. 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

How many doublings until 100 passes 1000?

money = 100
years = 0
while money < 1000:
    money = money * 2
    years = years + 1
print(years, money)
Step by step
  1. L3100 < 1000: True, enter the loop.money = 100
  2. L4Double: 200. years = 1.money = 200, years = 1
  3. L4400 (2), 800 (3), 1600 (4)...money = 1600, years = 4
  4. L31600 < 1000: False, the loop ends.
  5. L6Print once after the loop.4 1600

Sum until 0

Try it yourself

Edit the Input box: any numbers, ending with 0.

total = 0
n = int(input())
while n != 0:
    total = total + n
    n = int(input())
print(total)
Input (one line per input() call)
5
8
2
0
Step by step
  1. L2Read the first number before the loop.n = 5
  2. L35 != 0, so add it.total = 5
  3. L5Read the next number at the end of the round.n = 8
  4. 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)
  1. A
    27
  2. B
    9
  3. C
    20
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)
  1. A
    -1
  2. B
    1
  3. C
    0
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.

  1. PredictHalving

    Type exactly what this program prints.

  2. ModifyAlso count them

    The program adds numbers until 0. Also print, on a second line, how many numbers were added (not counting the 0).

  3. 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

TermChineseDefinition
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.