Python for beginners · Lesson 9 of 15

while loops, break and continue

Repeat code as long as a condition is true with while, stop a loop with break, skip a round with continue, and build a number-guessing game.

About 15 minutes · code runs in your browser, nothing to install

A for loop goes through items you already have. A while loop loop is different: it keeps repeating as long as its condition is True. Use it when you do not know in advance how many rounds you need.

Pythoneditable
count = 3
while count > 0:
    print(count)
    count -= 1
print("Lift off!")
Output
3
2
1
Lift off!

Here is a question a for loop cannot answer easily: how many months of saving 150 does it take to reach 1000?

Pythoneditable
savings = 0
months = 0
while savings < 1000:
    savings += 150
    months += 1
print(f"{months} months, {savings} saved")
Output
7 months, 1050 saved
Watch out: If the condition never becomes False, the loop runs forever. Make sure something inside the loop moves it towards the end, such as count -= 1.

Stop with break

break statement leaves the loop immediately. A common pattern is while True: (a loop that would run forever) with a break when the user is done.

Pythoneditable
while True:
    command = input("> ")
    if command == "quit":
        print("Bye!")
        break
    print("You typed:", command)
Output
> You typed: hello
> You typed: help
> Bye!

Typed answers: hello, help, quit

Skip a round with continue

continue statement jumps straight back to the top of the loop and skips the rest of the current round. Here it skips every multiple of 3.

Pythoneditable
n = 0
while n < 10:
    n += 1
    if n % 3 == 0:
        continue
    print(n)
Output
1
2
4
5
7
8
10

Project: a guessing game

Real games pick a random secret number. Here the secret is fixed and the guesses are typed in for you, so the output is always the same. The loop runs until the guess is right.

Pythoneditable
secret = 37
tries = 0
print("Guess my number between 1 and 100.")
while True:
    guess = int(input())
    tries += 1
    if guess < secret:
        print(guess, "is too low.")
    elif guess > secret:
        print(guess, "is too high.")
    else:
        print(f"Yes, {secret}! You needed {tries} tries.")
        break
Output
Guess my number between 1 and 100.
50 is too high.
25 is too low.
Yes, 37! You needed 3 tries.

Typed guesses: 50, 25, 37

A while loop is also the classic way to keep asking until the answer is valid. str.isdigit() is True only when a string contains nothing but digits.

Pythoneditable
while True:
    text = input()
    if text.isdigit():
        break
    print(f"'{text}' is not a whole number, try again.")
print("Thanks, you chose", int(text))
Output
'ten' is not a whole number, try again.
'-3' is not a whole number, try again.
Thanks, you chose 7

Typed answers: ten, -3, 7

✎ Exercise

Read numbers typed by the user and add them up until they type 0. Then print Total: followed by the total. The typed numbers are 4, 10, 6 and 0.

Hint: Use while True:, read with int(input()), break when the number is 0, otherwise add it to total.

Your codewrite your answer, then Run
total = 0
# your code here

Expected output:

Total: 20
Show a solution
Solutioneditable
total = 0
while True:
    number = int(input())
    if number == 0:
        break
    total += number
print("Total:", total)
Output
Total: 20

Check yourself

1. How many times does the body of x = 1 / while x < 4: x += 1 run?

2. What does continue do?

3. Why does while True: not run forever in the guessing game?

Spotted a mistake on this page? Tell us