Making Decisions
A program that always does the same thing is not very useful. Conditionals let it choose a path based on whether a condition is true. The basic form is if: if a boolean condition holds, run one block; optionally, an else block runs when it does not.
if temperature > 30:
print("hot")
else:
print("not hot")
The condition is a boolean expression — one that evaluates to true or false. Comparison operators produce booleans: == (equal), != (not equal), <, >, <=, >=. A frequent bug is confusing == (comparison) with = (assignment).
Boolean operators combine conditions. and is true only when both sides are true; or is true when at least one side is true; not flips a boolean. Their truth tables are worth memorizing:
| A | B | A and B | A or B |
|---|---|---|---|
| T | T | T | T |
| T | F | F | T |
| F | T | F | T |
| F | F | F | F |
Conditions can be chained with else if (or elif) to test several cases in order; the first matching branch runs and the rest are skipped. Many languages also short-circuit: in A and B, if A is false the whole thing is already false, so B is never evaluated — which matters when B has side effects or could error.
Common pitfall: writing=(assignment) where you mean==(comparison) in a condition.if x = 5tries to assign rather than compare, and in many languages is a bug or error. The condition of anifmust be a comparison or boolean, using==, not a single=.