liveBook · Manning

Break statement

As explained in A Pythonic Adventure: From Python basics to a working web app

A break statement immediately terminates the innermost loop and continues execution after it.

When a menu must keep asking until the user enters an acceptable choice, place the prompt inside a while True loop. A break statement ends the innermost loop immediately and continues with the code after it. section 4.0

A menu that stops at the right moment

while True: choice = input(prompt) if choice in allowed_answers: answer = choices[int(choice) - 1] break else: print("Enter a valid number") return answer Invalid input reaches the message and repeats the loop. A valid choice reaches break, so the function returns the selected answer instead of asking again. section 4.0

Keep these details in view:

  • Indent every statement belonging to the loop. section 4.0
  • Use break only after the desired condition succeeds. section 4.0
  • Try changing the menu so X or x exits without selecting an item. section 4.0

How A Pythonic Adventure: From Python basics to a working web app covers it

How deep it goes
Explains break within a while True input loop and shows its placement, but does not develop broader loop-control cases.
Examples
Demonstrates a drinks menu that rejects invalid answers and accepts numbered choices or X/x to exit.
What it assumes
Assumes input, conditionals, functions, and indentation while reinforcing indentation through editor checks.
What you can do after
Build it from scratch by adding a while loop and break to a menu function.
How it connects
Links break with while loops, input validation, conditional statements, indentation, and functions.

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 A Pythonic Adventure: From Python basics to a working web app. The section links point to the parts of the book it draws on.