Need to act only when a task meets a criterion? Evaluate a condition with `if`, then put the action in its indented body. Add `else` when an alternative action is needed. This is basic Python knowledge that carries across application domains. section 1.4.1 section 5.2.4
Keep only urgent task titles
Given task objects with `title` and `urgency` attributes, a loop can test each task before appending its title: `filtered_titles = [] for task in tasks: if task.urgency > 3: filtered_titles.append(task.title)` For the example tasks, `filtered_titles` is `['Homework', 'Museum']`. If the goal is simply to construct a list, the comprehension `[task.title for task in tasks if task.urgency > 3]` expresses the same filter more compactly. Its trailing `if` decides which items contribute to the result; it does not select between two result values. section 5.2.4
filtered_titles1 = [task.title for task in tasks if task.urgency > 3] assert filtered_titles0 == filtered_titles1
Compare the comprehension with the loop result to check that both retain the same task titles. section 5.2.4
Choose the form that matches the job:
- Use a standalone `if` when the condition controls an action. For filtering, it can make the test more conspicuous than `filter()`. section 5.3.6
- Use `value_when_true if condition else value_when_false` when one condition selects a value. For example, `[] if tags is None else tags` supplies an empty tag list when no tags were passed. section 10.3.2
- Put `break` inside an `if` when a loop should stop as soon as it finds what it needs. Initialize any result variable before the loop so it remains available if no item matches. section 5.4.1
Stop at the first match
`for number in range(5): print(f"Number: {number}") if number == 2: print("Breaking at 2") break` This prints `Number: 0`, `Number: 1`, `Number: 2`, and `Breaking at 2`; the remaining numbers are not visited. The same pattern can stop a task search at its first urgent match. section 5.4.1
A useful scope check is to assign a variable before an `if...else` statement, change it inside a branch, and inspect it afterward. This tests whether the statement creates a separate local scope; do not assume its behavior from another language. section 10.4.5




















