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.
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.
count = 3
while count > 0:
print(count)
count -= 1
print("Lift off!")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?
savings = 0
months = 0
while savings < 1000:
savings += 150
months += 1
print(f"{months} months, {savings} saved")7 months, 1050 saved
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.
while True:
command = input("> ")
if command == "quit":
print("Bye!")
break
print("You typed:", command)> 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.
n = 0
while n < 10:
n += 1
if n % 3 == 0:
continue
print(n)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.
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.")
breakGuess 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.
while True:
text = input()
if text.isdigit():
break
print(f"'{text}' is not a whole number, try again.")
print("Thanks, you chose", int(text))'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.
total = 0
# your code here
Expected output:
Total: 20
Show a solution
total = 0
while True:
number = int(input())
if number == 0:
break
total += number
print("Total:", total)Total: 20
Check yourself
1. How many times does the body of x = 1 / while x < 4: x += 1 run?
x goes 1, 2, 3 (body runs each time) and then 4, where x < 4 is false. That is 3 rounds.
2. What does continue do?
continue skips the rest of this round. break is the one that leaves the loop.
3. Why does while True: not run forever in the guessing game?
while True would run forever on its own; the break inside the loop ends it when the guess is right.