The break statement immediately stops the innermost enclosing loop. It works in both for and while loops, even when the loop condition remains true. section 18.3 section 18.4
Stop after too many guesses
A guessing program checks whether the player has reached 100 tries. When tries == max_tries becomes true, it prints a message and executes break. Statements remaining inside the loop do not run. Execution then continues after the loop, so a later conditional checks whether the player actually guessed the secret word before printing congratulations. section 18.3
Listing 18.4. Using the break keyword
secret = "code"
max_tries = 100
guess = input("Guess a word: ")
tries = 1
while guess != secret:
print("You tried to guess", tries, "times")
if tries == max_tries:
print("You ran out of tries.")
break #1
guess = input("Guess again: ")
tries += 1
if tries <= max_tries and guess == secret: #2
print("You got it!") #2
Trace a complete while-loop example showing the break condition, the immediate exit, and the check that determines why the loop ended. section 18.3
Keep these loop behaviors distinct:
- Use break to exit the innermost loop prematurely. section 18.4
- Use continue to skip the remaining statements in the innermost loop and begin its next iteration. section 18.4
- Check the result after a loop when more than one event can end it. section 18.3






