All courses › Programming with Python › Conditionals: if/elif/else

Conditionals: if/elif/else

if, elif and else let the program choose between branches based on conditions. Python checks the branches in order and runs only the first one that is true. Chained comparisons like 5 < x < 10 work directly.

if P1:…elif P2:…else:…\text{if } P_1: \ldots \text{elif } P_2: \ldots \text{else}: \ldotsthe first true PiP_i decides which branch runs

Symbols

P1, P2P_1,\ P_2conditions checked in order

Example

x = 18

if x < 4: ... elif x < 7: ... else: print("C")

Since 18≮418 \not< 4 and 18≮718 \not< 7, "C" is printed.

elif is only checked if all earlier conditions were false — order matters.
Practise loops and conditions for free →

← while loop · break and continue →

Part of Programming with Python: Loops and conditions.