Python reference
if, elif and else
Also called: conditional · branch · elif · decision
Definition
if runs a block only when its condition is true; elif tests another condition if earlier ones were false; else catches everything left.
Picture it
Python checks the branches top to bottom and takes the first true one, so order matters. Put the most specific tests first, and make sure every possible input lands in exactly one branch, including edge values such as exactly 30.
Worked example
With temp = 30, what does this choose? if temp > 35: fan = 3 elif temp >= 30: fan = 2 elif temp >= 25: fan = 1 else: fan = 0
- 30 > 35 is false
- 30 >= 30 is true → fan = 2, and the rest are skipped
Answerfan = 2.
✓ The number in this answer is recomputed from scratch by an automated test.
Common misconceptions
- Misconception: Separate if statements are all checked; elif stops at the first match.
- Misconception: if x == 1 or 2 is always true; write if x in (1, 2).