Skip to main content

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

Beginner25 min6 exercises70 XP
0/6 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
Loading editor...

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
Loading editor...

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
Loading editor...

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 your height, then check your age. You can put an if statement inside another if statement — this is called nesting.

Nested if statements
Loading editor...

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
Loading editor...

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
Loading editor...

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
Loading editor...

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

Loading editor...
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
    Loading editor...
    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.

    Loading editor...
    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
    Loading editor...
    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
    Loading editor...
    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
    Loading editor...

    Summary: Python If-Else Statements

    Here's everything you learned about Python conditionals:
    ---------
    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](/python/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.