Conditionals & modulo arithmetic
Programs become intelligent when they can choose different paths based on incoming conditions. Learn how Python evaluates Truthiness and executes conditional branches.
- Write conditions that evaluate to True or False.
- Check even vs odd numbers using the modulo operator (%).
- Chain multiple decisions using if, elif, and else.
if / elif / else blocks and comparison operators.
Comparison operators: ==, !=, >, <, >=, <=. The modulo operator % is vital for checking parity (e.g. num % 2 == 0 for even numbers). Python uses 4-space indentation to define blocks.
Checking Even vs Odd with Modulo (%)
The modulo operator (%) returns the remainder of a division. Any number divided by 2 with remainder 0 is even; otherwise, it is odd.
Treasure Island branching logic
Day 3's iconic project: a choose-your-own-adventure game where each decision leads deeper into the island or causes Game Over.
Control Flow Visualizer: Nested Decision Tree
Follow the execution pointer through nested IF conditions to the win branch.
| Variable | Value in Memory | Data Type |
|---|---|---|
| direction | "left" | str |
Player selected 'left'.
direction = "left"🔧 Assignment vs Comparison Bug
A condition mistakenly used single = instead of double ==, throwing a SyntaxError.
Predict The Output (2 Questions)
Your lightbulb moment
The key takeaway
Branching lets code make decisions. In Python, four-space indentation marks which instructions belong to each decision branch.
Make it yours
Try changing choice1 to 'right' and rerun the code to see how the branch skips directly to Game Over.
Try editing the code in the playground above in Python, JavaScript, Java, or C++, and use the step-by-step Dry-Run Table to inspect how variables mutate in memory. If you get stuck, click the 🤖 AI Doubt Solver button on your screen for instant explanations!