Python if, elif and else

Make decisions in your programs with comparisons, if, elif, else and logical operators.

Lesson 15 of 107Beginner18 min read

Programs become interesting when they can make decisions. Should the game say "You win" or "Try again"? Is the password long enough? Is it a weekend? An if statement checks a condition and runs a block of code only when that condition is true.

Python's version is short and readable: if, optional elif (short for "else if") branches, and an optional else that catches everything else. The lines that belong to each branch are shown by indentation, the four spaces at the start of the line.

In this lesson you'll compare values, write if/elif/else chains, and combine conditions with and, or and not.

Comparison operators

A comparison asks a question and the answer is a boolean: True or False.

OperatorMeaningExampleResult
==equal to5 == 5True
!=not equal to5 != 3True
> / <greater / less than7 > 9False
>= / <=greater or equal / less or equal18 >= 18True

Don't confuse = and ==. One equals sign stores a value; two equals signs compare two values.

if, elif and else

Python
temperature = 23

if temperature > 28:
    print("It's hot. Drink water!")
elif temperature > 15:
    print("Nice weather for a walk.")
else:
    print("Take a jacket.")
  • Each condition line ends with a colon :.
  • The lines underneath are indented by four spaces. They form the block for that branch.
  • Python checks the conditions from top to bottom and runs only the first branch that's true. Here 23 isn't above 28, but it is above 15, so the second message prints.
  • else has no condition. It runs when none of the others matched.

Indentation is the block

Python doesn't use curly braces. Instead, every indented line under the if belongs to it, and the first line that goes back to the left edge is outside it:

Python
if age >= 18:
    print("You can vote.")
    print("Remember to register.")
print("This line always runs.")

Use four spaces per level. Most editors insert them automatically when you press Tab in a .py file.

and, or, not

  • and is true only when both sides are true.
  • or is true when at least one side is true.
  • not flips a boolean: not True is False.
Python
has_ticket = True
age = 12

if has_ticket and age >= 12:
    print("Enjoy the film!")

You can also chain comparisons the way you would in maths: 13 <= age <= 19 checks whether someone is a teenager.

Truthy and falsy values

A condition doesn't have to be a comparison. Python can test any value directly, treating some values as false and everything else as true:

Falsy valuesTruthy examples
False, NoneTrue
0, 0.01, -3, 0.5
"" (empty string)"hello", " "
[], {}, (), set()[0], {"a": 1}

This lets you write short, readable checks:

Python
name = input("Name: ").strip()
if name:
    print(f"Hello, {name}")
else:
    print("You didn't type a name.")

if name: is true for any non-empty string. Be careful when 0 is a valid value: if score: treats a score of 0 as "no score". In that case test explicitly with if score is not None:.

Nested ifs and one-line conditional expressions

An if can sit inside another if when the second question only makes sense after the first is answered:

Python
logged_in = True
is_admin = False

if logged_in:
    if is_admin:
        print("Admin dashboard")
    else:
        print("Your account")
else:
    print("Please log in")

Deep nesting gets hard to follow, so combine conditions with and when you can.

For a simple choice between two values, Python has a conditional expression that fits on one line:

Python
age = 15
ticket = "child" if age < 16 else "adult"
print(ticket)   # child

Read it as "child if age is under 16, otherwise adult". Use it for short value choices only; anything with several steps belongs in a normal if statement.

When a block is required but you have nothing to put in it yet, write pass. It does nothing, but keeps the indentation valid while you sketch out a program.

Python if Statements Syntax

if / elif / else

if condition:
    # runs when condition is True
elif other_condition:
    # runs when the first was False and this is True
else:
    # runs when nothing above was True

Python if Statements Summary

  • Comparisons such as ==, !=, > and <= give True or False.
  • if condition: runs its indented block only when the condition is true.
  • elif adds more checks; else catches everything left over.
  • Only the first matching branch runs.
  • Combine conditions with and, or and not.

Python if Statements Examples

Each example shows the code, the output it produces and what each part does.

Example 1

Grade calculator

Python
score = 78

if score >= 90:
    grade = "A"
elif score >= 75:
    grade = "B"
elif score >= 60:
    grade = "C"
else:
    grade = "Keep practising"

print(f"Score {score}: {grade}")
Output
Score 78: B
Line-by-line explanation
  1. Line 378 is not 90 or more, so Python moves on.
  2. Line 578 is 75 or more, so grade becomes "B" and the rest of the chain is skipped.
  3. Line 12This line is not indented, so it runs whatever happened above.
Example 2

Even or odd

Python
number = 17

if number % 2 == 0:
    print(f"{number} is even")
else:
    print(f"{number} is odd")
Output
17 is odd
Line-by-line explanation
  1. Line 3% gives the remainder. Even numbers have a remainder of 0 when divided by 2.
  2. Lines 5 to 6Only two possibilities, so a plain if/else is enough.
Example 3

Combining conditions

Python
day = "Saturday"
raining = False

is_weekend = day == "Saturday" or day == "Sunday"

if is_weekend and not raining:
    print("Let's go to the park.")
elif is_weekend:
    print("Board games at home.")
else:
    print("School day.")
Output
Let's go to the park.
Line-by-line explanation
  1. Line 4A comparison can be stored in a variable. is_weekend holds True.
  2. Line 6Both parts must be true: it's the weekend, and it's not raining.
  3. Line 8Only reached if the first test failed.

Common Python if Statements Mistakes

Using = instead of ==

Don't
if colour = "red":
    print("Stop")
Do
if colour == "red":
    print("Stop")

A single = stores a value and isn't allowed in a condition, so Python shows a SyntaxError.

Forgetting the colon or the indent

Don't
if lives == 0
print("Game over")
Do
if lives == 0:
    print("Game over")

Every if, elif and else line needs a colon, and its block must be indented.

Checking the loose condition first

Don't
if score >= 50:
    print("Pass")
elif score >= 90:
    print("Excellent")  # never reached
Do
if score >= 90:
    print("Excellent")
elif score >= 50:
    print("Pass")

Python if Statements in Real Projects

Decisions everywhere

Login screens check if password_is_correct, shops check if total >= 50 before removing the delivery charge, and games check if health <= 0 to end a level. Almost every feature you can think of contains at least one if statement.

Python if Statements FAQ

Does Python have a switch statement?

Python 3.10 added the match statement, which compares a value against several patterns and is the closest equivalent to switch. On older versions, and for simple range checks such as grades, an if/elif chain is the normal approach. A dictionary that maps keys to values also replaces many simple switches.

What is the difference between elif and several separate if statements?

In an if/elif chain, Python stops at the first true condition, so at most one branch runs. Separate if statements are each checked, so several of them can run. Use elif when the options are mutually exclusive, like grades, and separate ifs when each check is independent.

Can I write an if statement without an else?

Yes. else is optional. If the condition is false and there is no else, Python simply skips the block and carries on with the next unindented line.

How do I check if a value is one of several options?

Use in with a tuple or set instead of chaining or: if day in ("Saturday", "Sunday"):. A common bug is writing if day == "Saturday" or "Sunday":, which is always true because the non-empty string "Sunday" is truthy on its own.

Why do I get IndentationError in my if statement?

The lines inside an if block must all be indented by the same amount, usually four spaces, and the block can't be empty. Mixing tabs and spaces also causes this error. Set your editor to insert spaces when you press Tab, and use pass as a placeholder for an empty block.

Python if Statements Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Fill in the blankseasy

Complete the code so it prints "Too cold" when temp is below 10, and "OK" otherwise.

temp = 4
 temp < 10:
    print("Too cold")
:
    print("OK")
Predict the outputeasy

What does this print?

x = 10
if x > 5:
    print("big")
elif x > 8:
    print("bigger")
else:
    print("small")
Multiple choicemedium

Which condition is True when age is between 13 and 19, inclusive?

Predict the outputmedium

What does this print?

logged_in = False
is_admin = True

if logged_in and is_admin:
    print("Admin panel")
elif not logged_in:
    print("Please log in")
else:
    print("Welcome")
Predict the outputhard

What does this print?

age = 15
if age >= 18:
    print("adult")
elif age >= 13:
    print("teen")
elif age >= 5:
    print("child")

Python if Statements Quiz

5 questions to check what you learned.

  1. What does == do in Python?

    • Stores a value
    • Checks whether two values are equal
    • Checks whether two values are different
    • Joins two strings
  2. What must come at the end of an if line?

    • A semicolon
    • Curly braces
    • Nothing
    • A colon
  3. How many branches of an if/elif/else chain can run at once?

    • All the true ones
    • Exactly two
    • At most one
    • It depends on the indentation
  4. What is the value of not (5 > 3 and 2 > 4)?

    • True
    • False
    • None
    • An error
  5. What does not (5 > 3) evaluate to?

    • False
    • True
    • 5
    • An error