Python if, elif, and else: Conditional Statements Explained
Python uses if, elif, and else to choose which code runs based on a condition. The first true condition wins, and Python skips the rest. This article shows how the statement works, how to read it, and the mistakes that most often confuse beginners.
Difficulty: Beginner
Helpful to know first: basic Python syntax, variables, comparison operators, and indentation.
How Python Chooses One Branch and Skips the Rest
A conditional statement lets your program make a decision. You test a condition such as age >= 18, and Python runs one block if that condition is true. If it is false, Python can try the next condition with elif, or fall back to else.
The important idea is that Python checks conditions from top to bottom. As soon as one condition is true, Python runs that block and ignores the remaining branches in the same chain.
age = 20
if age >= 18:
print("Adult")
else:
print("Minor")
# Output: AdultHere, age >= 18 is true, so Python prints Adult. The else block is skipped because it only runs when the if condition is false.
How if, elif, and else Work Together
Use if for the first test. Add one or more elif branches when you need extra checks. Finish with else when you want a default answer if nothing else matched.
Only one block in the chain runs. That makes these statements useful when your choices are mutually exclusive, such as grading a score or classifying a temperature.
Using if for the first decision
The if keyword starts the chain. The condition after it must evaluate to True or False.
temperature = 31
if temperature > 30:
print("Hot")
# Output: HotThis block runs because temperature > 30 is true. If the condition were false, Python would skip the indented block completely.
Using elif to test another condition
elif means “else if.” It lets you check another condition only if every earlier condition was false. This keeps the logic in one chain instead of writing separate if statements.
score = 82
if score >= 90:
print("A")
elif score >= 80:
print("B")
else:
print("C")
# Output: BPython checks score >= 90 first. That is false. Then it checks score >= 80, which is true, so it prints B and stops.
Using else for the fallback case
else handles everything not covered by the earlier conditions. It is the default branch.
day = "Sunday"
if day == "Saturday" or day == "Sunday":
print("Weekend")
else:
print("Weekday")
# Output: WeekendThe else block runs only when the day is not Saturday or Sunday. In this example, the condition is true, so Python prints Weekend.
How Indentation Defines the Blocks
Python uses indentation, not braces, to mark which statements belong to each branch. Every line inside the if, elif, or else block must be indented the same amount.
If the indentation is wrong, Python cannot tell where one branch ends and another begins. That is why many beginners see IndentationError or expected an indented block.
x = 10
if x > 0:
print("Positive")
print("Still inside the if block")
else:
print("Not positive")
# Output: Positive
# Output: Still inside the if blockBoth print() calls under the if are part of the same block because they are equally indented. The else belongs to the outer conditional chain, so it is aligned with if.
Real Examples of Conditional Logic in Python
Checking whether a number is even or odd
A common beginner example is testing divisibility with the remainder operator %. If a number divided by 2 leaves no remainder, it is even.
number = 7
if number % 2 == 0:
print("Even")
else:
print("Odd")
# Output: OddPython first calculates number % 2. Because 7 % 2 is 1, the condition is false, so the else block runs.
Choosing a message based on age
You can use several branches to model a real decision. Here, the program chooses a ticket price based on age.
age = 12
if age < 5:
print("Free")
elif age < 18:
print("Child ticket")
else:
print("Adult ticket")
# Output: Child ticketThe order matters. Python checks the first condition first, then the second. Because 12 < 18 is true, the program prints Child ticket.
Handling empty and non-empty input
Conditions do not need to compare numbers. Many Python values are already treated as true or false in a condition. Empty strings, empty lists, and zero are falsey; non-empty values are truthy.
name = "Ava"
if name:
print("Name provided")
else:
print("No name")
# Output: Name providedBecause the string is not empty, the condition is true. This style is common when checking for user input or optional data.
How Python Evaluates Conditions in Order
Python does not evaluate every branch in a chain. It starts at the top and stops at the first true condition. That means the order of your tests can change the result.
This matters most when conditions overlap. For example, a number greater than 90 is also greater than 80. If you test the broader condition first, the more specific branch never runs.
score = 95
if score >= 80:
print("Pass")
elif score >= 90:
print("Excellent")
# Output: PassThis output may surprise beginners. Even though 95 >= 90 is true, Python never reaches the elif because the first condition already matched. To fix this kind of logic, put the most specific condition first.
A long chain of overlapping conditions is a sign that the order needs a careful review. The top branch should usually be the narrowest match.
Predict the Output
Which branch runs when conditions overlap?
x = 5
if x > 0:
print("positive")
elif x > 3:
print("large")
else:
print("other")What does this print?
Show answer
It prints positive. The first condition, x > 0, is true, so Python runs that block and skips the elif and else. The second test is never evaluated.
What happens with a false condition and no else?
logged_in = False
if logged_in:
print("Welcome")
print("Done")What happens?
Show answer
Only Done prints. The if condition is false, so its block is skipped. Because there is no else, Python continues with the next line after the conditional statement.
Common Mistakes with Python if, elif, and else
Using separate if statements instead of one chain
Beginners often write multiple if statements when they mean one decision tree. That can cause more than one branch to run.
Problem: This code uses two separate if statements, so both can print when the value matches both tests.
score = 95
if score >= 80:
print("Pass")
if score >= 90:
print("Excellent")Fix: Use one if / elif / else chain when the choices should be exclusive.
score = 95
if score >= 90:
print("Excellent")
elif score >= 80:
print("Pass")The corrected version works because Python stops after the first matching branch.
Putting the broad condition before the specific one
When conditions overlap, the first true one wins. If the first test is too broad, later branches become unreachable in practice.
Problem: This code checks for x > 0 before the more specific x > 10, so the second branch never runs for values above 10.
x = 15
if x > 0:
print("Positive")
elif x > 10:
print("Large positive")Fix: Put the most specific condition first, then the broader one.
x = 15
if x > 10:
print("Large positive")
elif x > 0:
print("Positive")The fixed version works because the more specific case gets a chance to match first.
Forgetting the indentation after the colon
Every branch must have an indented block after the colon. If you leave it out, Python raises a syntax error.
Problem: This code has no indented block after if, so Python cannot parse it.
logged_in = True
if logged_in:
print("Welcome")Fix: Indent the statements that belong to the branch.
logged_in = True
if logged_in:
print("Welcome")The corrected version works because Python can now see which line belongs to the if block.
Using assignment instead of comparison
In a condition, beginners sometimes write = when they mean ==. Python does not allow assignment inside a condition like that, so the program fails to parse.
Problem: The condition uses assignment instead of comparison, which is not valid syntax in Python.
name = "Mina"
if name = "Mina":
print("Hello")Fix: Use == to compare values.
name = "Mina"
if name == "Mina":
print("Hello")The fixed version works because == checks equality instead of trying to reassign the variable.
Find the Bug
This code is meant to label a number as negative, zero, or positive. It looks reasonable, but one branch is wrong because of the order of the conditions. Find the bug.
number = 0
if number <= 0:
print("Negative")
elif number == 0:
print("Zero")
else:
print("Positive")Show answer
The bug is that number <= 0 matches zero too, so the elif branch never runs. The program prints Negative for 0, which is wrong for this task.
Fixed code:
number = 0
if number < 0:
print("Negative")
elif number == 0:
print("Zero")
else:
print("Positive")The fixed version works because the zero case gets its own exact test before the positive fallback.
When to Use if, elif, and else Versus Other Structures
Use an if chain when you want one decision from several possibilities. If you need to repeat an action for many items, use a loop instead. If you need to choose among many exact values, a dictionary lookup may be clearer than a long chain.
| Situation | Good choice | Why |
|---|---|---|
| Choose one of a few ranges | if / elif / else | Readable and direct for ordered checks |
| Choose from exact values | Dictionary or match | Can be shorter and easier to extend |
| Run code only when a condition is true | if | No fallback branch needed |
| Run code repeatedly | for or while | Conditionals do not repeat by themselves |
A long chain is not automatically wrong, but if you are comparing many exact labels, a dictionary or match may read better than many elif branches.
Interview Questions About Python Conditionals
What is the difference between if and elif?
if starts a conditional chain. elif adds another test that runs only if every earlier condition was false.
Why does order matter in an if chain?
Because Python stops at the first true condition. If a broad condition comes first, it can hide a more specific branch later in the chain.
Can you use only else without if?
No. else must follow an if or elif. It is never used by itself.
Try It Yourself
Write a small program that classifies a temperature:
- Print Freezing if the temperature is below 0.
- Print Cold if it is from 0 to 15 inclusive.
- Print Warm for anything above 15.
Expected output for temperature = 12:
ColdHint: check the smallest range first, then the next one.
Show solution
temperature = 12
if temperature < 0:
print("Freezing")
elif temperature <= 15:
print("Cold")
else:
print("Warm")Summary
- if starts a decision based on a condition that is true or false.
- elif adds another test only if earlier tests failed.
- else handles the default case when no earlier condition matched.
- Python checks conditions from top to bottom and stops at the first true branch.
- Indentation defines which lines belong to each block.
- For overlapping conditions, put the most specific test first.
Next, learn nested if statements so you can make a decision inside another decision.