Skip to main content
Editor

Python If-Else: Conditions, Elif, Nested Ifs, and Ternary

Beginner25 min7 exercises100 XP

Leer en españolЧитать на русскомLer em portuguêsอ่านภาษาไทย

0/7 exercises

Every day you make hundreds of decisions. If it's raining, you grab an umbrella. If the traffic light is red, you stop. If your phone battery is below 20%, you look for a charger. These are all conditional decisions - you check something and act based on the result.

Programs make decisions the same way. Without conditions, code would run the exact same way every single time - no matter what data it receives. Conditions let your programs respond to different situations, handle edge cases, and behave intelligently.

In this tutorial, you'll learn how Python makes decisions using if, else, and elif. By the end, you'll be writing programs that choose different paths based on user input, calculated values, and complex combinations of conditions.

How Does the Python if Statement Work?

The if statement is the simplest form of decision-making. It checks a condition. If the condition is True, the indented code below it runs. If the condition is False, Python skips that code entirely.

A basic if statement
temperature = 35
if temperature > 30:
print('It\'s hot outside!')
print('Stay hydrated.')
print('Have a great day!')
Output
It's hot outside!
Stay hydrated.
Have a great day!

Notice the structure. The if keyword is followed by a condition (temperature > 30), then a colon (:). The lines below it are indented - that's how Python knows which code belongs inside the if block. The last line runs no matter what because it's not indented under the if.

Try changing the temperature to 25 in the code above and run it again. The two lines about heat will disappear, but you'll still see "Have a great day!" because it's outside the if block.


Adding else: What Happens When the Condition Is False?

An if statement alone can only do something or do nothing. But often you want to do one thing when the condition is true and a different thing when it's false. That's what else is for.

if-else: two possible paths
age = 15
if age >= 18:
print('You can vote!')
else:
print('You\'re too young to vote.')
years_left = 18 - age
print(f'Come back in {years_left} years.')
Output
You're too young to vote.
Come back in 3 years.

Think of if-else like a fork in the road. Python always goes one way or the other - never both, never neither. Exactly one block runs every time.

Without else: two separate checks
score = 85

if score >= 60:
    print('You passed!')
if score < 60:
    print('You failed.')
With else: cleaner and safer
score = 85

if score >= 60:
    print('You passed!')
else:
    print('You failed.')

The version with else is better for two reasons. First, it's shorter and easier to read. Second, it's impossible to accidentally have both blocks run or neither block run. With two separate if statements, a typo in the second condition could cause bugs.


How Does elif Work for Multiple Conditions?

What if you have more than two options? Imagine grading a test: A, B, C, D, or F. You can't handle five outcomes with just if and else. That's where elif (short for "else if") comes in.

elif chains for multiple conditions
score = 82
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
elif score >= 60:
grade = 'D'
else:
grade = 'F'
print(f'Score: {score}, Grade: {grade}')
Output
Score: 82, Grade: B

Python checks the conditions from top to bottom. The moment it finds one that's True, it runs that block and skips everything below it. If none of the conditions match, the else block runs as a safety net.

You can have as many elif blocks as you want. The else at the end is optional - but it's good practice to include it as a catch-all for unexpected values.


Nested If Statements: Conditions Inside Conditions

Sometimes you need to check a second condition only after a first one passes. For example, a theme park ride might first check that you have a ticket, then check your age. You can put an if statement inside another if statement - this is called nesting.

Nested if statements
has_ticket = True
age = 14
if has_ticket:
if age >= 12:
print('Welcome to the ride!')
else:
print('Sorry, you must be 12 or older.')
else:
print('You need a ticket first.')
Output
Welcome to the ride!

The inner if only runs when the outer if is True. Notice how the indentation gets deeper - each level of nesting adds another layer of indentation.

Deeply nested: harder to read
if has_ticket:
    if age >= 12:
        if height >= 120:
            print('Welcome!')
Combined conditions: cleaner
if has_ticket and age >= 12 and height >= 120:
    print('Welcome!')

Python Ternary Operator: One-Line If-Else

Sometimes you have a simple if-else that just assigns a value. Python has a shortcut for this called the ternary operator (also called a conditional expression). It puts the entire if-else on one line.

Ternary operator: one-line if-else
age = 20
# Regular if-else
if age >= 18:
status = 'adult'
else:
status = 'minor'
print(status)
# Same thing with ternary operator
status = 'adult' if age >= 18 else 'minor'
print(status)
Output
adult
adult

The syntax is: value_if_true if condition else value_if_false. Read it like English: "status is 'adult' if age is at least 18, else 'minor'."

Ternary in practice
# Ternary works great in print statements and f-strings
temperature = 28
print(f'Wear a {"coat" if temperature < 15 else "t-shirt"} today.')
# And for quick calculations
x = -5
absolute = x if x >= 0 else -x
print(f'Absolute value of {x} is {absolute}')
Output
Wear a t-shirt today.
Absolute value of -5 is 5

Common Mistakes with If-Else

Here are the most frequent bugs beginners make with conditional statements. Learn to recognize these patterns and you'll save yourself hours of debugging.

Common mistake: or with multiple values
# Bug: wrong comparison for multiple values
color = 'red'
# This does NOT work as expected
if color == 'red' or 'blue':
print('This always runs!') # Always True!
# This is correct
if color == 'red' or color == 'blue':
print('Red or blue!')
# Even cleaner with "in"
if color in ('red', 'blue', 'green'):
print('Primary color!')
Output
This always runs!
Red or blue!
Primary color!

Practice Exercises

Time to practice! These exercises build from simple if statements to more complex conditional logic. Try each one before looking at hints.

Exercise 1: Even or Odd
Write Code

Write a program that checks if a number is even or odd. A variable number is given with the value 7.

Print "even" if the number is even, or "odd" if it's odd.

Expected output:

odd

Hint: A number is even if number % 2 == 0 (the remainder when dividing by 2 is zero).

number = 7
# Check if the number is even or odd
Exercise 2: Temperature Advisor
Write Code

Write a program that gives clothing advice based on temperature. A variable temp is given with the value 22.

Rules:

  • If temp is 30 or above, print "Wear shorts"
  • If temp is 20 or above (but below 30), print "Wear a t-shirt"
  • If temp is 10 or above (but below 20), print "Wear a jacket"
  • Below 10, print "Wear a coat"
  • Expected output:

    Wear a t-shirt
    temp = 22
    # Give clothing advice based on temperature
    Exercise 3: Predict the Output
    Predict Output

    Without running the code, predict what it will print. Then run it to check.

    Think carefully about which conditions are True and which are False.

    x = 15
    if x > 20:
    print('A')
    elif x > 10:
    print('B')
    elif x > 5:
    print('C')
    else:
    print('D')
    print('Done')
    Exercise 4: Fix the Grade Calculator
    Fix the Bug

    This grade calculator has a bug. Every score gets the grade "D" even when it should be "A", "B", or "C". Fix the elif chain so it works correctly.

    Expected output for score = 85:

    Grade: B
    score = 85
    if score >= 60:
    grade = 'D'
    elif score >= 70:
    grade = 'C'
    elif score >= 80:
    grade = 'B'
    elif score >= 90:
    grade = 'A'
    else:
    grade = 'F'
    print(f'Grade: {grade}')
    Exercise 5: Ternary Ticket Price
    Write Code

    A movie theater charges $12 for adults (age 18 or over) and $8 for children (under 18). Use the ternary operator to set the price in one line, then print it.

    A variable age is given with the value 14.

    Expected output:

    Ticket price: $8
    age = 14
    # Use a ternary operator to set the price
    price = # your code here
    print(f'Ticket price: ${price}')
    Exercise 6: Login Validator
    Write Code

    Write a login validator. Two variables are given: username and password.

    Rules:

  • If username is "admin" and password is "secret123", print "Welcome, admin!"
  • If username is "admin" but password is wrong, print "Wrong password"
  • For any other username, print "User not found"
  • Expected output for username = "admin", password = "wrong":

    Wrong password
    username = 'admin'
    password = 'wrong'
    # Write the login validation logic
    The Next Day
    Stretch

    Write a function next_day(day, month, year) that returns the date of the following day as text in the form "YYYY-MM-DD".

    next_day(14, 3, 2026)   # '2026-03-15'
    next_day(30, 4, 2026)   # '2026-05-01'

    The rules of the calendar:

  • April, June, September and November have 30 days. February has 28, or 29 in a leap year. Every other month has 31.
  • A year is a leap year when it divides by 4, except years that divide by 100, which are leap years only when they also divide by 400. So 2024 and 2000 are leap years, 1900 and 2026 are not.
  • Return the answer instead of printing it: Check calls next_day() with its own dates, some of them hidden.

    def next_day(day, month, year):
    pass
    Solution unlocks after your first Check

    Summary: Python If-Else Statements

    Here's everything you learned about Python conditionals:

    ConceptSyntaxPurpose
    ifif condition:Run code when condition is True
    elseelse:Run code when if is False
    elifelif condition:Check additional conditions
    Nested ifif inside ifMulti-level decisions
    Ternaryx if cond else yOne-line if-else for simple values

    Key rules to remember:

  • Every if, elif, and else line ends with a colon (:)
  • Code inside the block must be indented
  • In an elif chain, Python stops at the first True condition
  • Use == for comparison, not = (which is assignment)
  • Put the most restrictive condition first in elif chains
  • What's Next?

    Now that you can make decisions, it's time to make your programs repeat things. In the next tutorial - Python For Loops - you'll learn how to loop through lists, ranges, and strings to process data without writing the same code over and over.

    Harder problems

    More problems on this topic: Python Basics

    Related Tutorials

    Was this tutorial helpful?