Python if, elif and else
1Python If...Else: overview
An if statement lets a program make a decision: it checks a condition and runs a block of code only when that condition is True, with elif and else covering the other cases.
Before this lesson: Python Data Types, Python Operators
2Python If...Else: diagram
3Python If...Else: explained step by step
Until now, Python has run every line of your program from top to bottom. An if statement lets the program decide whether to run a block of code, depending on whether a condition is True or False.
The if statement
Write if, then a condition, then a colon. The indented lines underneath form the block that runs only when the condition is true:
temperature = 31
if temperature > 30:
print("Hot day: drink some water")
print("Weather check finished")Change temperature to 20 and run it again: the indented line is skipped, but the last line still runs because it's outside the block.
else: the other path
else: introduces the block to run when the condition is false. Exactly one of the two blocks runs — never both, never neither.
elif: choosing between several options
When there are more than two possibilities, add elif ("else if") branches. Python checks the conditions from top to bottom and runs the block of the first one that is true. Everything after that is skipped, even conditions that would also be true.
score = 82
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print("Grade:", grade)Because only the first match counts, order matters. A score of 95 is also >= 80, but it never gets that far because >= 90 is tested first. Put the strictest condition at the top.
Truthy and falsy values
A condition doesn't have to be a comparison. Python can treat any value as true or false: 0, 0.0, empty text "", None and empty collections are falsy, and almost everything else is truthy. That makes checks such as "was a name entered?" short and readable:
name = ""
if name:
print("Hello,", name)
else:
print("Please enter your name")Combining and nesting conditions
Use and, or and not to combine several tests in one condition, and chain comparisons to check a range, just as you would in maths: if 0 <= score <= 100:.
You can also put an if inside another if. The inner block is indented one more level and is only reached when the outer condition is true. Nesting suits questions that only make sense after an earlier answer, but more than two or three levels becomes hard to follow — often and or elif reads better.
One-line choices
To pick between two values, Python offers a compact conditional expression: status = "adult" if age >= 18 else "minor". It's great for short, simple choices; use a full if statement for anything longer.
Quick reference: Python If...Else
- Python Control Flow Cheat Sheet: if, for, while, match — Python control flow uses `if`/`elif`/`else` to choose, `for` and `while` to repeat, `break` and `continue` to…
- How to Check if a List Is Empty in Python — Write `if not my_list:` to check whether a list is empty. An empty list is falsy, so `not my_list` is `True` …
- Python Program to Check Even or Odd Number — To check if a number is even or odd in Python, test `number % 2 == 0`: a remainder of 0 means the number is e…
- Python Simple Calculator Program — A simple Python calculator reads two numbers and an operator with `input()`, then uses `if/elif` (or a dictio…
- Python BMI Calculator Program — A BMI calculator computes `weight_kg / height_m ** 2` and uses `if/elif` to name the category: below 18.5 und…
- Python Program to Check Leap Year — A year is a leap year if it is divisible by 4, except century years, which must also be divisible by 400; in …
- Python FizzBuzz Program — FizzBuzz asks you to print the numbers 1 to 100, replacing multiples of 3 with `Fizz`, multiples of 5 with `B…
4Python If...Else: syntax
if condition:
... # runs when condition is True
elif other_condition:
... # checked only if everything above was False
else:
... # runs when no condition was True
if 0 <= x <= 100: # chained comparison
label = "yes" if ok else "no" # one-line choice
5Python If...Else: run the example
Press Run (or Ctrl + Enter). The output (step 6) appears directly below the code. Change anything and run it again.
student = "Leo"
score = 82
handed_in_late = True
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print(student, "got a", grade)
if handed_in_late:
if grade == "A":
print("Late, but still top marks")
else:
print("Late: please hand in on time next week")
print("Valid score:", 0 <= score <= 100)Expected outputLeo got a B
Late: please hand in on time next week
Valid score: True
7Python If...Else: how the example works
Hover or tap a step to highlight its lines in the example above.
- Line 1-3The data to decide on: a name, a score and a True/False flag.
- Line 5-6Python tests
score >= 90first. 82 is not ≥ 90, so the condition is False and line 6 is skipped. - Line 7-8Next it tries the
elif:82 >= 80is True, sogradeis set to"B". - Line 9-12A branch has already run, so Python skips the remaining
elifand theelsewithout even testing them. - Line 13This line is back at the left edge, outside the chain, so it always runs.
- Line 15
handed_in_lateis already a bool, so it can be the condition on its own — no== Trueneeded. It's True, so Python enters the block. - Line 16-19A nested decision, indented one level further.
grade == "A"is False, so the innerelseprints the reminder. - Line 20A chained comparison:
0 <= score <= 100means0 <= score and score <= 100. Both parts are true, so it printsTrue.
8Python If...Else: common mistakes
Putting the conditions in the wrong order
✗ Wrong
score = 95
if score >= 70:
grade = "C"
elif score >= 90:
grade = "A"
print(grade)✓ Right
score = 95
if score >= 90:
grade = "A"
elif score >= 70:
grade = "C"
print(grade)Python stops at the first true condition, and 95 >= 70 is already true, so the A branch is never reached. Test the highest threshold first.
Forgetting the colon
✗ Wrong
age = 20
if age >= 18
print("Adult")✓ Right
age = 20
if age >= 18:
print("Adult")Every if, elif and else line must end with a colon — it tells Python that an indented block follows.
Using separate ifs where you meant elif
✗ Wrong
temp = 35
if temp > 30:
print("Hot")
if temp > 20:
print("Warm")
else:
print("Cold")✓ Right
temp = 35
if temp > 30:
print("Hot")
elif temp > 20:
print("Warm")
else:
print("Cold")Each if starts a new, independent decision, so both tests run. Use elif to join the branches into one chain where only one can run.
9Python If...Else: exercises
Write your answer, then press Check. The checks run in your browser.
1. Even or odd?
Write code Easy ✓ CompletedUsing if and else, set the variable kind to "even" when number is even or "odd" when it is odd, then print kind. A number is even when the remainder after dividing by 2 is 0.
Try a few other values for number to see both branches work, then set it back to 17 and press Check.
number = 17
# set kind with if / elsenumber = 17
if number % 2 == 0:
kind = "even"
else:
kind = "odd"
print(kind)
2. Which branches run?
Predict the output Medium ✓ CompletedRead the code and type exactly what it prints. Notice which lines start a new decision and which belong to an existing one.
x = 15
if x > 10:
print("big")
elif x > 5:
print("medium")
if x % 2 == 0:
print("even")
else:
print("odd")
if "":
print("empty text is truthy")
print("done")big
odd
done
2 more exercises → 4 more examples
Questions learners ask
What is the difference between elif and a second if?
elif belongs to the same chain as the if above it, so it is only checked when every earlier condition was False — at most one branch of the chain runs. A second if starts a new, independent decision that is always checked, so several blocks can run.
Is else required after an if statement?
No, else is optional. Use it when something should happen in the "none of the above" case. Without it, Python simply carries on with the next line when no condition is true.
Does Python have a switch statement?
Python 3.10 added match/case, which compares one value against several patterns. For simple checks such as ranges of numbers, an if/elif/else chain is still the most common and readable choice.
Further reading
10Next lesson
Up nextPython Logical ConditionsA logical condition joins several True/False tests with and, or and not, so a single if statement can weigh more than o…Related:
Python Logical ConditionsPython Nested IfPython Shorthand If (Ternary)
← Python Input and Output · All Control Flow lessons · Practise in the IDE