liveBook · Manning

Break statement

As explained in Python Workout: 50 ten-minute exercises

A Python control-flow statement that immediately terminates the innermost enclosing loop.

When a loop should stop at a meaningful condition, use break to terminate the innermost enclosing loop immediately. A common pattern starts with while True and exits after a successful guess or an empty order. section 1.3 section 4.4

Stop a guessing loop

Choose an answer with random.randint, repeatedly read the user's input, convert it with int, and compare it with the answer. When the guess is correct, break exits the loop. The same control-flow shape supports a menu-ordering program: strip the input, use if not order for empty input, and break before processing further. section 1.3 section 4.4

Use break when:

  • A sentinel condition signals that repeated interaction is finished. section 4.4
  • A successful search or comparison makes further iterations unnecessary. section 1.3

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Defines innermost-loop termination and demonstrates it in two interactive programs, without developing nested-loop behavior.
Examples
Uses a number-guessing game and a menu-ordering loop that stops on empty input.
What it assumes
Uses while loops, conditional tests, input strings, and integer conversion in its worked interactions.
What you can do after
Apply it via Python control flow to end interactive loops at explicit success or sentinel conditions.
How it connects
Connects break with while loops, input conversion, random number generation, dictionaries, and truth-value testing.

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 Python Workout: 50 ten-minute exercises. The section links point to the parts of the book it draws on.