Find a course

Module 3: Decisions and LoopsLesson 7 of 1013 min

while Loops and a Guessing Game

Repeat code until a condition changes with while loops, avoid infinite loops, use break, and build a number-guessing game with the random module.

Step 1 of 13Learn

Repeat until something happens

A for loop is great when you know how many times to repeat. But how many guesses will a player need? How many times will a user type the wrong password? You can't know in advance. A while loop repeats as long as its condition is True:

battery = 100
while battery > 0:
    print(f"Battery: {battery}%")
    battery -= 25
print("Phone off")

Python checks the condition, runs the block, then goes back and checks again. This prints 100, 75, 50 and 25, then the condition battery > 0 is False and the loop ends.

If the condition is False the very first time, the block never runs at all.

The most important rule: something inside the loop must eventually make the condition False. Here, battery -= 25 does that. Delete that line and the battery stays at 100 forever. That's an infinite loop: the program keeps printing until you stop it by force (Ctrl+C in most terminals, or the stop button in an editor).

Step 2 of 13Practice · Diagram

How a while loop runs

Which step, if you delete it, causes an infinite loop?

Tap the shape that answers the question, then press Check.

How a while loop runsCycle diagram: Check the condition → Run the block → Change the variable.whilebattery > 0Check theconditionRun the blockChange thevariable
Check the condition

False? Leave the loop and continue below it.

Run the block

print(f"Battery: {battery}%")

Change the variable

battery -= 25 moves it toward False.

Step 3 of 13Practice · Work it out

How many times does this loop print "jump"? `` height = 1 while height < 20: print("jump") height = height * 2 ``

Step 4 of 13Learn

break and input loops

A common pattern is to keep asking until the user gives a valid answer:

answer = ""
while answer != "yes" and answer != "no":
    answer = input("Continue? (yes/no) ").strip().lower()
print("You chose", answer)

Starting answer as an empty string makes sure the loop runs at least once.

Sometimes it's simpler to loop "forever" and jump out from the middle with break:

while True:
    code = input("Enter the door code: ")
    if code == "4521":
        print("Door open!")
        break
    print("Wrong code, try again.")

while True would be an infinite loop on its own, but break exits the loop immediately, skipping anything left in the block. Use this when the stopping decision naturally happens in the middle of the loop, after reading input.

break works in for loops too, for example to stop searching once you've found what you're looking for.

Step 5 of 13Compare

for or while?

Aspectfor loopwhile loop
Use it whenYou know how many times, or you have a sequence to walk throughYou repeat until something changes and can't predict when
ExamplePrint a 10-second countdown; check each letter of a wordAsk for a password until it is right; run a game until lives reach 0
How it stopsAutomatically, when the sequence runs outWhen the condition becomes False, or at a break
Typical bugOff-by-one in range()Forgetting to update the variable, causing an infinite loop

Step 6 of 13Practice · Choose one

Which loop is an infinite loop?

Step 7 of 13Practice · Code challenge · Python

Code challenge · Python

You are saving up for a new game. Complete weeks_to_save(price, per_week) so it returns how many weeks it takes until your savings reach at least price, if you start at 0 and add per_week every week. Use a while loop.

For example, weeks_to_save(60, 15) returns 4, and weeks_to_save(65, 15) returns 5. If the price is 0, you need 0 weeks.

The def line and the return are already written for you; you will learn exactly how they work in the Functions lesson. Fill in the middle.

Real Python, running in a sandbox in your browser.
  • weeks_to_save(60, 15)
  • weeks_to_save(65, 15)
  • weeks_to_save(10, 25)
  • weeks_to_save(0, 10)

Step 8 of 13Learn

Random numbers and modules

Games need unpredictability: dice rolls, loot drops, enemy moves. Python's random module provides it. A module is a file of ready-made code; you load it with import:

import random

roll = random.randint(1, 6)
print("You rolled", roll)

random.randint(a, b) returns a random whole number from a to b, and unlike range, it includes both ends. So randint(1, 6) can return 6. random.choice(["rock", "paper", "scissors"]) picks one item at random.

Now you have everything for a classic game:

import random

secret = random.randint(1, 100)
guesses = 0
while True:
    guess = int(input("Guess (1-100): "))
    guesses += 1
    if guess < secret:
        print("Too low")
    elif guess > secret:
        print("Too high")
    else:
        print(f"Got it in {guesses} guesses!")
        break

A clever player halves the range each time (guess 50, then 25 or 75, and so on). That strategy, called binary search, always finds a number from 1 to 100 in at most 7 guesses, because 2 to the power 7 is 128.

Step 9 of 13Practice · Chart

1,000 rolls of random.randint(1, 6)

Which face came up most often in this run?

Tap the bar that answers the question, then press Check.

1,000 rolls of random.randint(1, 6)Bar chart with 6 categories: 1: 163; 2: 171; 3: 158; 4: 176; 5: 162; 6: 170.050100150200Count123456Face163171158176162170
Illustrative result of one simulated run. Each face has a 1 in 6 chance, so each lands near 167; run it again and the bars change.
1,000 rolls of random.randint(1, 6)
FaceTimes rolled
1163
2171
3158
4176
5162
6170

Step 10 of 13Practice · Select all that apply

random.randint(1, 4) could return which of these values? Select all that apply.

Select all that apply.

Step 11 of 13Note

Step 12 of 13Practice · Spot the mistake

This loop should keep asking until the user types "quit". Tap the line that turns it into an infinite loop.

Step 13 of 13Practice · What would you do?

What would you do?

In the guessing game, a friend suggests changing secret = random.randint(1, 100) so it sits inside the while True: loop, right before the input line. What would happen?