Making Decisions
A program that always does the same thing is not very useful. Conditionals let code choose a path based on whether a condition is true, using if and optional else blocks.
The condition must be a boolean expression evaluating to true or false. Comparison operators build these:
| Operator | Meaning | Example |
|---|---|---|
== | Equal | x == 5 |
!= | Not equal | x != 5 |
<, > | Less / Greater | x > 0 |
<=, >= | Less/Greater-equal | x <= 10 |
Common pitfall: Confusing == (comparison) with = (assignment). Writing if x = 5 tries to assign a value instead of comparing it, causing a syntax or logic error.
Combining Conditions
Boolean operators combine multiple expressions. Short-circuiting means evaluation stops early if the outcome is already known.
| Operator | Rule | Short-Circuit Behavior |
|---|---|---|
and | True if both sides are true | If left is false, stops and returns false |
or | True if at least one side is true | If left is true, stops and returns true |
not | Flips the boolean value | N/A |
Chain cases using else if (or elif). The first matching branch runs, and all subsequent branches are skipped entirely.