liveBook · Manning

Break statement

As explained in Python How-To

A break statement immediately terminates the innermost enclosing loop.

Need the first task with a particular urgency level? A `break` statement ends the current `for` or `while` loop immediately. Put it inside an `if` statement so the loop stops when the match is found, rather than checking the remaining items. section 5.4.1 section 5.4

Find the index of a matching task

```python class Task: def __init__(self, title, urgency): self.title = title self.urgency = urgency tasks = [Task("Laundry", 3), Task("Museum", 4), Task("Homework", 5), Task("Ticket", 2)] needed_task_index = None for task_i in range(len(tasks)): if tasks[task_i].urgency == 5: needed_task_index = task_i break print(f"Task Index: {needed_task_index}") # Task Index: 2 ``` The loop stops at the first match. Initializing the result to `None` also leaves a defined value if no task matches. section 4.3.4 section 5.4.1

The same conditional pattern works in a `while` loop: when `break` runs, execution leaves the loop even if its condition would otherwise allow another iteration. section 5.4.1

Handle a search that finds nothing

```python for task in tasks: if task.urgency == 5: print(f"Found: {task.title}") break else: print("No matching task") # Found: Homework ``` A loop’s `else` block runs only when the loop finishes without executing `break`. Use it when that distinction matters; without a possible `break`, the `else` block would run anyway. section 5.4.3

How Python How-To covers it

How deep it goes
Explains immediate exit from `for` and `while` loops through conditional examples and a practical search.
Examples
Uses numbered loop output and urgency-based task searches to show where iteration stops.
What it assumes
Assumes basic `for` or `while` loops and `if` conditions; introduces `break` with small runnable examples.
What you can do after
Apply it to stop searching after a match and distinguish a match from normal loop completion.
How it connects
Connects `break` to conditional statements, `for` loops, `while` loops, and loop `else` clauses.

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