Programming Fundamentals › Programming Basics
Conditional (if/else)
Running different code depending on a condition.
Also known as: if else, if statement, conditional statement, branching, if/else
A conditional runs different code depending on whether a condition is true. It’s how programs make decisions.
if age >= 18:
print("adult")
elif age >= 13:
print("teen")
else:
print("child")
if (age >= 18) { ... } else if (age >= 13) { ... } else { ... }
The conditions are checked top to bottom, and only the first branch whose condition is true runs.
Things to know
- Conditions are booleans, or values the language treats as true or false (truthy and falsy).
- Order matters: put the most specific condition first.
if age >= 13beforeif age >= 18would catch adults too. =vs==:=assigns,==compares (and in JavaScript, prefer===, see == vs ===).- Combine conditions with
and/or(&&/||), and use parentheses when mixing them. - Avoid deep nesting. Use early returns (guard clauses).
- Cover the
else: what happens when none match? Unhandled cases cause bugs.
Alternatives
| For | Use |
|---|---|
| Choosing between many fixed values | a switch statement or a dictionary lookup |
| A simple value choice | a ternary operator: x = a if cond else b |
Replacing repeated if chains on type | polymorphism or a lookup table |
A function full of nested conditions is a sign to split it up. See control flow.