The docking bay game is the crew's favorite break-time puzzle. One person thinks of a bay number from 1 to 10, and the other guesses until they find it.
"I want the computer to run it," Rocket says. "But I cannot know how many guesses it will take. Could be one, could be ten."
Raven thinks about yesterday. "What do you notice?" she asks. "The loop should stop the moment the guess is right, wherever that happens inside the loop."
Nova hovers in a small circle and then darts straight out of it. "Would you like a hint?" she asks. "A loop can run forever on purpose, as long as it has a way out. That way out is called break."
Rocket writes while True and smiles.
while True: starts a loop whose condition is always True. On its own it would never stop. The break statement jumps out of the loop at once, and the program carries on after it.
This pattern is perfect for asking again and again until the user gives the answer you need.
# ready_loop.py
while True:
answer = input("Type go to launch: ").strip().lower()
if answer == "go":
break
print("Holding...")
print("Launching!") Type go to launch: wait Holding... Type go to launch: not yet Holding... Type go to launch: GO Launching!
# docking.py
secret = 7
tries = 0
while True:
guess = int(input("Guess the docking bay (1 to 10): "))
tries = tries + 1
if guess == secret:
break
elif guess < secret:
print("Higher")
else:
print("Lower")
print(f"Docked in {tries} tries!") Guess the docking bay (1 to 10): 5 Higher Guess the docking bay (1 to 10): 9 Lower Guess the docking bay (1 to 10): 7 Docked in 3 tries!
A loop can have more than one break. This one leaves when the launch word is right, or when the user has used three tries.
# three_tries.py
tries = 0
while True:
word = input("Launch word: ").strip().lower()
tries = tries + 1
if word == "nova":
print("Launch word accepted")
break
if tries == 3:
print("Three tries used. Take a break and try again later.")
break
print("Not that one. Try again.") Launch word: orbit Not that one. Try again. Launch word: comet Not that one. Try again. Launch word: moon Three tries used. Take a break and try again later.
| Statement | True or false? |
|---|---|
| A loop can have more than one break. | ? |
| break leaves only the if, not the loop. | ? |
| while True runs forever unless something breaks out. | ? |
| Lines after break in the same block still run. | ? |
while True with break is a tool you will use in the Mission Log menu later in the course. Tomorrow you will build a real countdown clock.