Python If...Else
Python · Control Flow
Theory
An if statement runs a block of code only when its condition is truthy. Python evaluates the condition after if; if it is true, the indented block runs and the rest of the chain is skipped. Otherwise it checks each elif condition in order, and if none is true, the else block runs. At most one branch of an if/elif/else chain ever runs, and both elif and else are optional. With salary = 85000, salary > 80000 is True, so level becomes 'Senior'.
Because conditions are checked top to bottom and the first match wins, order matters: put the most specific condition first. A common mistake is a boundary like > versus >=: with salary = 80000, salary > 80000 is False, so the person is 'Junior'. Any value can be a condition thanks to truthiness, so if items: means 'if the list is not empty'. For simple either/or values, the conditional expression level = 'Senior' if salary > 80000 else 'Junior' fits on one line.
Why we use it
Programs must react differently to different data: grade a score, apply a discount, flag an outlier. if/elif/else is the basic tool that turns a condition into a decision.
When to use it
Use if/elif/else for decisions with a few branches. Use the one-line conditional expression for choosing between two values. For mapping many fixed values to results, a dictionary lookup or a match statement is often cleaner.
How it works
- Reach the if statement
- Is salary > 80000 true? Yes: Run the if block: level = 'Senior'. No: Check the next branch.
- Any elif condition true? Yes: Run the first matching elif block. No: Run the else block: level = 'Junior'.
- Skip all remaining branches
- Continue after the chain: print(level)
Syntax
if condition:
...
elif other:
...
else:
...Example
if salary > 80000:
level = "Senior"
else:
level = "Junior"Key points
- elif chains multiple conditions; the first true one wins
- At most one branch of an if/elif/else chain runs
- Watch boundaries: > and >= differ at exactly 80000
- Ternary form: x if cond else y
- Any value works as a condition thanks to truthiness