Control Flow: If / Elif / Else
Published by Brayan K
Learn how to make your programs smart by having them make decisions based on conditions.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
if: run some lines only when a condition is true
An if statement is the word if, a condition, a colon, and an indented block of lines underneath. Python runs the block only when the condition is true, then carries on with the next line that isn't indented. Conditions are usually comparisons, built with the operators from Operators and Expressions:
temperature = 25
if temperature > 30:
print("Hot: drink some water.")
if temperature > 20:
print("Warm: no coat needed.")
print("Have a good day.")
# ✅ Expected output:
# Warm: no coat needed.
# Have a good day.25 isn't more than 30, so the first block is skipped. The second condition is true, so its block runs. The last line isn't indented, so it belongs to neither if and runs every time.
The colon and the indentation
Python knows which lines belong to the block only from their indentation, so both parts of the layout are rules, not style. Leave out the colon and the program stops before any of it runs:
temperature = 35
if temperature > 30
print("Hot")
# ✅ Expected error:
# SyntaxError: expected ':'Leave out the indentation and Python finds an if with nothing in it:
temperature = 35
if temperature > 30:
print("Hot")
# ✅ Expected error:
# IndentationError: expected an indented block after 'if' statement on line 2The message gives the line of the if that's missing its block. A comment doesn't count as a block either; to leave one for later, put pass in it, a statement that does nothing.
Indent with four spaces per level, which is what Python's style guide asks for, and set your editor to insert four spaces when you press Tab. If some lines of a block are indented with a tab and others with spaces, Python can stop with TabError: inconsistent use of tabs and spaces in indentation, even though the lines look lined up.
else: the other way
An else block runs when the condition above it is false, so exactly one of the two blocks runs, never both and never neither. else has no condition of its own:
age = 15
if age >= 18:
print("You can vote.")
else:
print("Not yet.")
print("Checked.")
# ✅ Expected output:
# Not yet.
# Checked.elif: more than two cases, and the first true one wins
For more than two cases, add elif branches between the if and the else. Python tests the conditions from the top and runs only the first branch whose condition is true. Every branch after it is skipped, even ones that would be true:
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print(grade)
# ✅ Expected output:
# B85 is also at least 70, but the score >= 70 branch is never tested. That's why the order of a chain matters. Put the lowest threshold first and it catches every score above it:
score = 95
if score >= 70:
grade = "C"
elif score >= 80:
grade = "B"
elif score >= 90:
grade = "A"
print(grade)
# ✅ Expected output:
# CWith >= thresholds, test the highest first. The else is optional, but it must come last, after every elif. If you know else if from another language, Python spells it elif, and the long form gives a confusing message, because Python expects the colon straight after else:
score = 85
if score >= 90:
print("A")
else if score >= 80:
print("B")
# ✅ Expected error:
# SyntaxError: expected ':'One chain or separate if statements?
A chain makes one decision: at most one of its branches runs, and exactly one when it ends with else. Separate if statements make separate decisions, each checked on its own. A cinema ticket needs both kinds, a price for the age and a discount on Tuesdays:
age = 15
day = "Tuesday"
if age < 5:
price = 0
elif age < 16:
price = 7.5
else:
price = 12
if day == "Tuesday" and price > 0:
price = price - 2
print(price)
# ✅ Expected output:
# 5.5The chain picks exactly one price. The Tuesday discount is a separate if, so it is checked every time, but only reduces a paid ticket, so the free ticket stays free. Ask yourself whether the cases exclude each other: if they do, write one chain; if they can all apply, write separate statements.
Two conditions that don't mean what they say
A single = assigns a value, so it can't be a condition. Python stops at once, and the message suggests the fix:
answer = 42
if answer = 42:
print("Correct")
# ✅ Expected error:
# SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?You want ==. The other suggestion, :=, assigns a value inside an expression, which isn't what you meant here; The Walrus Operator (:=) explains it.
The second bug gives no error at all, which makes it worse. In English, "if the colour is red or orange" is clear, but Python needs a full comparison on each side of or:
colour = "blue"
if colour == "red" or "orange":
print("warm colour")
else:
print("cool colour")
# ✅ Expected output:
# warm colourPython reads the condition as (colour == "red") or "orange". The comparison is False, so or gives back "orange", and text that isn't empty counts as true. The block runs whatever the colour is. Write the comparison out twice:
colour = "blue"
if colour == "red" or colour == "orange":
print("warm colour")
else:
print("cool colour")
# ✅ Expected output:
# cool colourcolour in ["red", "orange"] says the same thing more briefly, and reads better as the list grows.
Conditions that aren't comparisons
Any value can be a condition. Zero, empty text and None count as false, and nearly everything else counts as true, so if name: means "if name isn't empty":
name = ""
if name:
print("Hello,", name)
else:
print("Hello, stranger")
items = 3
if items:
print("Your basket has", items, "items")
# ✅ Expected output:
# Hello, stranger
# Your basket has 3 itemsFor the same reason, if is_member == True: can be written if is_member:. Take care when 0 is a real answer, though: if stock: is false for a stock of 0, so write if stock > 0: when that's what you mean. Booleans & Truthiness lists every value that counts as false.
An if inside an if, and flattening it
A block can hold another if; each level of nesting is indented four more spaces:
age = 25
has_id = False
if age >= 18:
if has_id:
print("Come in.")
else:
print("Show your ID, please.")
else:
print("Over-18s only.")
# ✅ Expected output:
# Show your ID, please.Every extra level is one more thing to hold in your head. Handling the problem cases first, in one chain, keeps every branch at the same level, with the normal case last:
age = 25
has_id = False
if age < 18:
print("Over-18s only.")
elif not has_id:
print("Show your ID, please.")
else:
print("Come in.")
# ✅ Expected output:
# Show your ID, please.Inside a function, the same idea is called a guard clause: check for a problem, leave the function early with return, and keep the main work unindented. Functions introduces return.
Shorter ways to choose
Two shorter forms build on if, and each has its own lesson. A conditional expression picks one of two values in a single line:
label = "adult" if age >= 18 else "minor"Conditional Expressions (Ternary) shows when that helps and when a full if reads better. And match compares one value against a list of patterns, which can replace a long elif chain of == tests; it's in Structural Pattern Matching (match/case).
Practice: a shipping charge
Orders of 50 or more ship free, members pay 2 and everyone else pays 5. Orders from 40 up to 50 also get a nudge to spend a little more. Fill the three blanks with the words in the hint lines, in order, and run it.
total = 45
member = True
if total >= 50:
shipping = 0
___ member:
shipping = 2
___:
shipping = 5
print("Shipping:", shipping)
if total >= 40 ___ total < 50:
print("Spend", 50 - total, "more for free shipping")
# 👉 replace ___ with elif
# 👉 replace ___ with else
# 👉 replace ___ with and
# ✅ Expected output:
# Shipping: 2
# Spend 5 more for free shippingOn your own: postage for a parcel
Postage starts at £3.99. A parcel over 10 kg costs £5.00 more, and one over 2 kg but not over 10 kg costs £2.00 more. Sending it more than 100 km adds £4.50, and express delivery doubles the whole price. Write a program that prints the price of a 6.5 kg parcel going 250 km by express; it should come to £20.98. Then compare it with this solution:
weight = 6.5
distance = 250
express = True
price = 3.99
if weight > 10:
price += 5.00
elif weight > 2:
price += 2.00
if distance > 100:
price += 4.50
if express:
price *= 2
print("Price:", round(price, 2))
# ✅ Expected output:
# Price: 20.98The weight bands are one chain, because a parcel is in exactly one band, and the over-10 band is tested first: the other way round, a 12 kg parcel would match "over 2 kg" and be charged £3.00 too little. Distance and express are separate if statements, because each one applies on top of whatever came before.
Practice quiz
score = 95. A chain tests score >= 70 for "C" first, then elif score >= 80 for "B", then elif score >= 90 for "A". Which grade does it give?
- A
- B
- C
- None of them
Answer: C. 95 >= 70 is already true, so the first branch runs and the rest are skipped. Test the highest threshold first.
colour = "blue", then if colour == "red" or "orange": print("warm") else: print("cool"). What prints?
- cool
- warm
- Nothing
- An error
Answer: warm. The right side of or is just "orange", which counts as true, so the if branch always runs. Write colour == "red" or colour == "orange".
What happens when Python meets the line if answer = 42: ?
- It stops with a SyntaxError before running anything
- It sets answer to 42 and runs the block
- It compares answer with 42
- It skips the block
Answer: It stops with a SyntaxError before running anything. = assigns and can't be used as a condition. The error message suggests ==.
n = 15, followed by two separate statements: if n > 10: print("A") and if n > 5: print("B"). What prints?
- A only
- B only
- Nothing
- A, then B
Answer: A, then B. Separate if statements are each checked. Only an elif would stop after the first true condition.
name = "". Which branch of if name: ... else: ... runs?
- The if branch
- The else branch
- Both
- Neither, because it's an error
Answer: The else branch. Empty text counts as false in a condition.
How does Python spell "else if"?
- else if
- elseif
- elif
- elsif
Answer: elif. elif. Writing else if stops the program with SyntaxError: expected ':'.
Which of these counts as false in a condition?
- "0"
- " "
- "False"
- 0
Answer: 0. The number 0 is false. The other three are text that isn't empty, so they all count as true.
temperature = 20. An if/elif chain prints cold when temperature < 0 and hot when temperature > 30, with no else. What does the chain print?
- cold
- hot
- Nothing
- It raises an error because else is required
Answer: Nothing. Neither condition is true, so neither branch runs. An else branch is optional.
Continue this course
- Previous: Operators and Expressions
- Next: Loops - For and While — Repeat actions automatically with for loops and while loops
- Quick reference: Python cheat sheet › Control Flow
Frequently asked questions
Do I need parentheses around an if condition?
No. if (age >= 18): works, but Python doesn't need the brackets, and most Python code leaves them out: if age >= 18:. Use parentheses inside a condition when they make the order clearer, as in if (a or b) and c:.
Can an if statement go on one line?
A block of one statement can follow the colon on the same line, as in if hot: print("Drink water"), but Python's style guide discourages it because it's harder to read. To choose between two values in one line, use a conditional expression, which has its own lesson.