liveBook · Manning

Break statement

As explained in Get Programming: Learn to code with Python

break is a Python control-flow statement that immediately terminates the innermost enclosing loop.

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

How Get Programming: Learn to code with Python covers it

How deep it goes
Explains immediate termination and post-loop handling, stopping short of deeper control-flow internals.
Examples
Uses a secret-word guessing game with a maximum-tries limit and a post-loop success check.
What it assumes
Assumes basic for and while loops, conditions, variables, input, and statements placed after a loop.
What you can do after
Practice/perform early loop exits and handle different termination reasons in guessing programs.
How it connects
Connects break with while loops, for loops, continue statements, and conditional statements.

Also explained in

Compare how 7 books explain break statement →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming: Learn to code with Python. The section links point to the parts of the book it draws on.