Python If…Else
Programs need to make decisions: grant access or not, pass or fail, discount or full price. Python makes these decisions with if, elif and else.
- Run code only when a condition is true
- Choose between branches with elif and else
- Nest conditions and combine them
- Write one-line conditional expressions
The if statement
if runs its indented block only when the condition is true.
temperature = 38 if temperature > 37.5: print("Fever detected") print("Please see a doctor")print("Check complete")Fever detected Please see a doctor Check complete
The condition can be any expression. Python treats it as true or false using the truthiness rules from Operators & Booleans.
if … else
else runs when the condition is false. Exactly one of the two blocks runs.
age = 16 if age >= 18: print("You can vote")else: print(f"You can vote in {18 - age} years")You can vote in 2 years
if … elif … else
elif (short for “else if”) checks another condition. Python tests the conditions from top to bottom and runs only the first block whose condition is true.
marks = 74 if marks >= 90: grade = "A"elif marks >= 75: grade = "B"elif marks >= 60: grade = "C"else: grade = "F" print("Grade:", grade)Grade: C
Order matters. If you test marks >= 60 first, a score of 95 would get “C”, because the first true branch wins and the rest are skipped.
Nested if
An if can sit inside another if. Each level adds 4 spaces of indentation.
username = "admin"password = "s3cret" if username == "admin": if password == "s3cret": print("Welcome, admin") else: print("Wrong password")else: print("Unknown user")Welcome, admin
Deep nesting is hard to read. Often you can flatten it with and:
username, password = "admin", "s3cret" if username == "admin" and password == "s3cret": print("Welcome, admin")else: print("Login failed")Welcome, admin
Combine conditions
day = "Saturday"is_holiday = Falsehour = 22 if day in ("Saturday", "Sunday") or is_holiday: print("Weekend rates apply") if not is_holiday and 9 <= hour <= 18: print("Office is open")else: print("Office is closed")Weekend rates apply Office is closed
Conditional expression (one-line if)
For a simple choice between two values, write the condition inline:
stock = 0status = "In stock" if stock > 0 else "Sold out"print(status) n = 7print("even" if n % 2 == 0 else "odd")Sold out odd
Empty blocks with pass
A block cannot be empty. Use pass as a placeholder while you are still writing the code:
feature_ready = False if feature_ready: pass # TODO: call the new featureelse: print("Using the old feature")Using the old feature
Common mistakes
Using = instead of == in a condition is a syntax error:
x = 5if x = 5: print("five") File "main.py", line 2
if x = 5:
^^^^^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?x == 1 or 2 does not check whether x is 1 or 2. It means (x == 1) or 2, and 2 is always truthy:
x = 7print(bool(x == 1 or 2)) # always True: a bugprint(x == 1 or x == 2) # correctprint(x in (1, 2)) # correct and shorterTrue False False
Check your understanding
Predict the output
n = 15if n % 3 == 0: print("Fizz")elif n % 5 == 0: print("Buzz")else: print(n)Fizz
15 is divisible by both 3 and 5, but only the first matching branch runs, so only “Fizz” prints. To print “FizzBuzz” you must test n % 15 == 0 first.
Quick quiz
1. How many branches of an if/elif/else chain run?
Python runs the first true branch (or else) and skips the rest.
2. What does "yes" if 0 else "no" evaluate to?
0 is falsy, so the else value is used.
3. Which correctly tests whether x is 1 or 2?
x == 1 or 2 is always truthy, and (1 or 2) is just 1.
Exercise: shipping cost
Orders of 500 or more ship free. Otherwise shipping is 40, or 80 for express. Print the shipping cost for each order.
(650, False), (300, False), (300, True)
Order 650: shipping 0 Order 300: shipping 40 Order 300: shipping 80
Hint 1
Check the free-shipping rule first.
orders = [(650, False), (300, False), (300, True)] for amount, express in orders: if amount >= 500: shipping = 0 elif express: shipping = 80 else: shipping = 40 print(f"Order {amount}: shipping {shipping}")Order 650: shipping 0 Order 300: shipping 40 Order 300: shipping 80
The free-shipping rule is tested first because it applies whether or not the order is express. The for line unpacks each tuple into amount and express.
Program Practice
64 Python If-Else Programs
Every program has a step-by-step explanation, colour-coded code and its real output.
Python if else FAQ
What is elif in Python?
elif means “else if”. It adds another condition to an if statement and is checked only when all the conditions above it were false.
Does Python have a switch statement?
Python 3.10 added match / case, which covers switch-style logic and much more. See Match Case.
How do I write an if else in one line in Python?
Use a conditional expression: result = "pass" if score >= 50 else "fail".
Can I have an if without an else?
Yes. else is optional. Without it, nothing happens when the condition is false.