Python If...Else
Beginner Control Flow

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.

GoalBy the end you can write if/elif/else chains, put conditions in the right order, use truthy and falsy values, nest decisions and chain comparisons like 0 <= x <= 100.

Before this lesson: Python Data Types, Python Operators

2Python If...Else: diagram

Python if, elif and elsescore = 82score >= 90Truegrade = "A"Falsescore >= 80Truegrade = "B"Falsescore >= 70Truegrade = "C"Falseelsegrade = "F"print(grade)
Python tests each condition from top to bottom and runs only the first branch that is True. With score = 82 the first test fails and the second passes, so grade becomes "B" and the remaining checks are skipped.

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:

Python
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.

Python
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:

Python
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

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.

Interactive example
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.

  1. Line 1-3The data to decide on: a name, a score and a True/False flag.
  2. Line 5-6Python tests score >= 90 first. 82 is not ≥ 90, so the condition is False and line 6 is skipped.
  3. Line 7-8Next it tries the elif: 82 >= 80 is True, so grade is set to "B".
  4. Line 9-12A branch has already run, so Python skips the remaining elif and the else without even testing them.
  5. Line 13This line is back at the left edge, outside the chain, so it always runs.
  6. Line 15handed_in_late is already a bool, so it can be the condition on its own — no == True needed. It's True, so Python enters the block.
  7. Line 16-19A nested decision, indented one level further. grade == "A" is False, so the inner else prints the reminder.
  8. Line 20A chained comparison: 0 <= score <= 100 means 0 <= score and score <= 100. Both parts are true, so it prints True.

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)
No error, but a score of 95 prints C

✓ 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")
SyntaxError: expected ':'

✓ 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")
No error, but it prints both Hot and Warm

✓ 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

Using 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.

Your code
number = 17

# set kind with if / else

2. Which branches run?

Predict the output Medium

Read the code and type exactly what it prints. Notice which lines start a new decision and which belong to an existing one.

Read this code
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")

2 more exercises → 4 more examples

Finished this lesson?
Progress is saved in this browser — create a free account to keep it across devices.

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