Python: if, elif, else
Master Python decisions with if, elif and else: comparison operators, branching, why elif beats stacked ifs, chained conditions with and/or, and indentation. Runnable code, a worked example and quiz.
Key takeaways
- if runs a block only when its condition is True; else runs when it is False
- elif lets you test extra conditions in order, choosing exactly one branch
- Comparisons like ==, !=, <, >, <=, >= produce the True/False values conditions need
- Indentation decides which lines belong to a branch, so it must be consistent
Programs that make decisions
So far, the programs you write probably run every line, top to bottom, the same way every time. But real programs need to choose. A game checks if you have enough points to win. A login checks if the password is correct. A shop checks if you are old enough to buy something. These choices are called conditionals, and in Python they are built from three keywords: if, elif, and else.
This lesson goes deeper than a first look at decisions. If if is brand new to you, skim conditionals in Python first; here we focus on combining if, elif, and else correctly and avoiding the classic traps.
Conditions: the True/False questions
Every decision rests on a condition β an expression that is either True or False. We build conditions with comparison operators:
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | equal to | 5 == 5 | True |
!= | not equal to | 5 != 3 | True |
> | greater than | 2 > 9 | False |
< | less than | 2 < 9 | True |
>= | greater than or equal | 7 >= 7 | True |
<= | less than or equal | 4 <= 3 | False |
The most common beginner bug is confusing = and ==:
x = 5assigns the value 5 to the variablex.x == 5asks "is x equal to 5?" and gives backTrueorFalse.
Inside an if, you almost always want the double ==.
The if statement
An if runs a block of code only when its condition is True:
temperature = 32
if temperature > 30:
print("It's hot!")
print("Stay hydrated.")
Reading it carefully:
if temperature > 30:is the condition, ending in a colon:.- The two indented lines are the block that runs only if the condition is True.
- Because
32 > 30is True, both lines print.
If the temperature were 18, the condition would be False and Python would simply skip the whole block.
Indentation is not optional
In Python, indentation (the spaces at the start of a line) decides which lines belong to the if. Lines indented under the if run together as the block. The moment a line goes back to the left, it is outside the if and runs every time:
if temperature > 30:
print("It's hot!") # part of the if
print("Have a nice day.") # NOT part of the if β always runs
Use four spaces per level, and be consistent. Mixing indentation causes an IndentationError.
Adding else: the fallback
An else block runs when the if condition is False. It gives you an "otherwise" path:
age = 15
if age >= 18:
print("You can vote.")
else:
print("Too young to vote.")
Exactly one of the two blocks runs. Since 15 >= 18 is False, the else block runs and prints "Too young to vote." There is no condition on else β it simply catches every case the if missed.
elif: choosing among many options
What if there are more than two possibilities? Stacking separate if statements is clumsy and can misbehave. Instead, use elif (short for "else if") to test extra conditions in order:
score = 75
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
elif score >= 60:
print("Grade: D")
else:
print("Grade: F")
Here is the key behaviour: Python checks the conditions top to bottom and runs only the first one that is True, then skips all the rest.
score >= 90? 75 is not, so move on.score >= 80? 75 is not, so move on.score >= 70? 75 is, so print "Grade: C" and stop β the remainingelifandelseare skipped entirely.
This ordering is why the chain works. We test the highest grade first and work down, so the first match is always the right one.
Why elif beats stacked ifs
Compare these two versions. They look similar but behave very differently:
# With elif β exactly ONE message
if score >= 70:
print("You passed.")
elif score >= 50:
print("Almost there.")
# With two separate ifs β can print BOTH
if score >= 70:
print("You passed.")
if score >= 50:
print("Almost there.")
With a score of 75 and separate ifs, both conditions are True, so you'd print "You passed." and "Almost there." β usually not what you want. With elif, only the first match runs. When the options are alternatives, reach for elif.
Combining conditions with and / or
Sometimes one test is not enough. You can join conditions with and and or:
andis True only when both sides are True.oris True when at least one side is True.
age = 16
if age >= 13 and age <= 19:
print("You are a teenager.")
if age < 13 or age > 19:
print("You are not a teenager.")
The first condition needs age to be at least 13 and at most 19. Since 16 fits both, it prints "You are a teenager." This is far cleaner than nesting two separate if statements.
Worked example: a ticket price calculator
Let's build a complete program that decides a cinema ticket price from the customer's age, using everything above.
age = int(input("How old are you? "))
if age < 5:
price = 0
message = "Free entry for little ones!"
elif age <= 17:
price = 8
message = "Child ticket."
elif age >= 65:
price = 6
message = "Senior discount applied."
else:
price = 12
message = "Adult ticket."
print(message)
print(f"Your ticket costs {price} pounds.")
Tracing it for a 70-year-old:
int(input(...))reads the age and converts the text to a number β70.age < 5? No. Skip.age <= 17? No. Skip.age >= 65? Yes. Setprice = 6and the senior message, then skip theelse.- The two prints show "Senior discount applied." and "Your ticket costs 6 pounds."
Notice the order matters: because the chain checks in sequence and stops at the first match, each branch only runs when all the earlier ones failed. That is what lets elif age <= 17 quietly mean "between 5 and 17" β anyone under 5 was already caught above.
Try it yourself
Write a program that gives feedback on a quiz score out of 100:
- Read the score with
int(input(...)). - Use an
if / elif / elsechain to print:"Outstanding!"for 90+,"Great job!"for 70β89,"Keep practising."for 50β69, and"Let's review together."below 50. - Add a single combined condition using
andthat prints a bonus message, such as "Perfect attendance bonus!" only when the score is at least 70 and a variableattended_allisTrue.
Check the boundaries carefully β what should happen at exactly 70 or exactly 90? Once your branches choose correctly every time, you are ready to repeat actions automatically with loops and repeats.
Quick quiz
Test yourself and earn XP
What is the difference between = and == in Python?
A single = stores a value in a variable. A double == compares two values and gives True or False. Using = inside an if is a common mistake.
In an if / elif / elif / else chain, how many branches run?
Python checks each condition in order and runs only the first True branch, then skips the rest. If none are True, the else block runs.
What does this print? ``` x = 7 if x > 10: print("big") elif x > 5: print("medium") else: print("small") ```
x > 10 is False, so it checks elif x > 5, which is True (7 > 5), so it prints 'medium' and skips the else.
When is the condition `age >= 13 and age <= 19` True?
and requires both parts to be True, so age must be at least 13 AND at most 19 β the teenage range, including 13 and 19.
Why does indentation matter after an if statement?
Python uses indentation to decide which lines belong to the if. Mis-indented lines either run at the wrong time or cause an IndentationError.
FAQ
Use elif when only one option should win and the conditions are related, like grading a score. Separate ifs each get checked independently, so more than one can run. An if/elif/else chain checks in order and runs exactly one branch, which is usually what you want for choosing between options.
No. else is optional. Use it when you want a fallback for every case the ifs and elifs did not catch. If doing nothing is fine when no condition matches, you can leave else out entirely.
Keep exploring
More in Coding