Branching (P2)¶
This page introduces branching: how a Python program makes decisions and chooses different paths of execution.
Branching depends directly on operators.
If operators produce True or False,
branching decides what to do next.
What Is Branching?¶
Branching is the ability of a program to execute different code blocks depending on a condition.
In Python, branching uses:
ifelifelse
Example:
If the condition is True, the block runs.
If it is False, the block is skipped.
The if Statement¶
An if statement evaluates a condition.
- The condition must evaluate to
TrueorFalse - The indented block runs only when the condition is
True
if / else¶
Use else when there are exactly two paths.
Only one branch will run.
if / elif / else¶
Use elif (else if) when there are multiple possible conditions.
Rules:
- Conditions are checked top to bottom
- The first True condition wins
- Only one block executes
Branching with Boolean Operators¶
Conditions often combine multiple comparisons using Boolean operators.
Branching with Membership Tests¶
Membership operators are common in data work.
Branching for Data Validation¶
Branching is often used to skip invalid data.
or:
Indentation Matters (Python Rule)¶
Branching blocks are defined by indentation, not braces.
Common Mistakes¶
Forgetting the colon¶
Misaligned indentation¶
How Branching Fits into Pipelines¶
Branching is used to:
- validate inputs
- skip bad rows
- choose output paths
- handle edge cases
Reminders¶
- Branching controls which code runs
- Conditions rely on operators
- Only one branch runs per
ifchain - Branching is essential for real data work