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






