Python If…Else

Python Tutorial › Control Flow › If…Else

Python If…Else

BeginnerLesson 13 of 4711 min read10 runnable examples

Programs need to make decisions: grant access or not, pass or fail, discount or full price. Python makes these decisions with if, elif and else.

In this lesson
  • Run code only when a condition is true
  • Choose between branches with elif and else
  • Nest conditions and combine them
  • Write one-line conditional expressions

The if statement

if runs its indented block only when the condition is true.

Python
temperature = 38 if temperature > 37.5:    print("Fever detected")    print("Please see a doctor")print("Check complete")
Output
Fever detected
Please see a doctor
Check complete

The condition can be any expression. Python treats it as true or false using the truthiness rules from Operators & Booleans.

if … else

else runs when the condition is false. Exactly one of the two blocks runs.

Python
age = 16 if age >= 18:    print("You can vote")else:    print(f"You can vote in {18 - age} years")
Output
You can vote in 2 years

if … elif … else

elif (short for “else if”) checks another condition. Python tests the conditions from top to bottom and runs only the first block whose condition is true.

Python
marks = 74 if marks >= 90:    grade = "A"elif marks >= 75:    grade = "B"elif marks >= 60:    grade = "C"else:    grade = "F" print("Grade:", grade)
Output
Grade: C
Watch out

Order matters. If you test marks >= 60 first, a score of 95 would get “C”, because the first true branch wins and the rest are skipped.

Nested if

An if can sit inside another if. Each level adds 4 spaces of indentation.

Python
username = "admin"password = "s3cret" if username == "admin":    if password == "s3cret":        print("Welcome, admin")    else:        print("Wrong password")else:    print("Unknown user")
Output
Welcome, admin

Deep nesting is hard to read. Often you can flatten it with and:

Python
username, password = "admin", "s3cret" if username == "admin" and password == "s3cret":    print("Welcome, admin")else:    print("Login failed")
Output
Welcome, admin

Combine conditions

Python
day = "Saturday"is_holiday = Falsehour = 22 if day in ("Saturday", "Sunday") or is_holiday:    print("Weekend rates apply") if not is_holiday and 9 <= hour <= 18:    print("Office is open")else:    print("Office is closed")
Output
Weekend rates apply
Office is closed

Conditional expression (one-line if)

For a simple choice between two values, write the condition inline:

Python
stock = 0status = "In stock" if stock > 0 else "Sold out"print(status) n = 7print("even" if n % 2 == 0 else "odd")
Output
Sold out
odd

Empty blocks with pass

A block cannot be empty. Use pass as a placeholder while you are still writing the code:

Python
feature_ready = False if feature_ready:    pass          # TODO: call the new featureelse:    print("Using the old feature")
Output
Using the old feature

Common mistakes

Using = instead of == in a condition is a syntax error:

Python
x = 5if x = 5:    print("five")
Output
  File "main.py", line 2
    if x = 5:
       ^^^^^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?

x == 1 or 2 does not check whether x is 1 or 2. It means (x == 1) or 2, and 2 is always truthy:

Python
x = 7print(bool(x == 1 or 2))       # always True: a bugprint(x == 1 or x == 2)        # correctprint(x in (1, 2))             # correct and shorter
Output
True
False
False

Check your understanding

Predict the output

n = 15if n % 3 == 0:    print("Fizz")elif n % 5 == 0:    print("Buzz")else:    print(n)

Quick quiz

1. How many branches of an if/elif/else chain run?

2. What does "yes" if 0 else "no" evaluate to?

3. Which correctly tests whether x is 1 or 2?

Exercise: shipping cost

Orders of 500 or more ship free. Otherwise shipping is 40, or 80 for express. Print the shipping cost for each order.

Input
(650, False), (300, False), (300, True)
Expected output
Order 650: shipping 0
Order 300: shipping 40
Order 300: shipping 80
Hint 1

Check the free-shipping rule first.

Program Practice

Python if else FAQ

What is elif in Python?

elif means “else if”. It adds another condition to an if statement and is checked only when all the conditions above it were false.

Does Python have a switch statement?

Python 3.10 added match / case, which covers switch-style logic and much more. See Match Case.

How do I write an if else in one line in Python?

Use a conditional expression: result = "pass" if score >= 50 else "fail".

Can I have an if without an else?

Yes. else is optional. Without it, nothing happens when the condition is false.