liveBook · Manning

Break statement

As explained in Python Workout, Second Edition

break is a Python statement that exits the innermost enclosing loop.

Use break when a loop should stop after a condition becomes true. A common pattern is while True, which creates an infinite loop, followed by input, processing, and a conditional break when the task is complete. break exits the innermost enclosing loop. section 2.3 section 5.9

When applying this pattern, keep the termination path explicit:

  • Begin an intentional infinite loop with while True. section 2.3
  • Read and convert input when the comparison requires matching types; input returns a string, while numeric comparisons require an integer. section 2.3
  • Place break in the success condition, such as a correct guess or the end of data entry. section 2.3 section 5.9

Two interactive loops

A number-guessing exercise repeats prompts until the user correctly guesses the randomly selected answer, then uses break to leave the loop. A rainfall tracker similarly gathers city names and amounts inside while True and stops only when break is encountered. section 2.3 section 5.9

How Python Workout, Second Edition covers it

How deep it goes
Explains the infinite-loop pattern and innermost-loop behavior, but does not develop broader loop-control variations.
Examples
Demonstrates break through a number-guessing loop and a rainfall dictionary program.
What it assumes
Assumes familiarity with while loops, conditionals, input, and basic type conversion.
What you can do after
Apply break to stop interactive Python loops at a clearly defined success or completion condition.
How it connects
Connects break with while loops, input conversion, comparison operators, dictionaries, and Boolean conditions.

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, Second Edition. The section links point to the parts of the book it draws on.