LearnFrenzy
Sign in Take a free test

Making Decisions · Lesson 9 of 39

if, elif and else

5 min read Updated Nov 7, 2026 Saurabh Samir

Up to now, every program ran every line. Real programs choose: show the dashboard if the login is correct, otherwise show an error. In Python that choice is made with if, elif and else.

In this lesson

  • The if statement and its flowchart
  • Two-way (else) and many-way (elif) decisions
  • Nested conditions and how to flatten them
  • The one-line conditional expression

The if statement

temperature = 38

if temperature > 35:
    print("It's hot – drink water!")
print("Have a good day.")

Output

It's hot – drink water!
Have a good day.

Three things make up an if: the keyword, a condition (anything that is truthy or falsy) and a colon. The indented lines below form the block that runs only when the condition is true.

if … else: two paths

balance = 1200
price = 1500

if balance >= price:
    print("Payment successful")
    balance -= price
else:
    print(f"Insufficient balance. You need ₹{price - balance} more.")

Output

Insufficient balance. You need ₹300 more.

if … elif … else: many paths

Use elif ("else if") to test several conditions in order. Python runs the first block whose condition is true and skips the rest.

marks = 82

if marks >= 90:
    grade = "A+"
elif marks >= 75:
    grade = "A"
elif marks >= 60:
    grade = "B"
elif marks >= 40:
    grade = "C"
else:
    grade = "Fail"

print(f"Marks {marks} → Grade {grade}")

Output

Marks 82 → Grade A

How Python walks through the chain (marks = 82)

  1. marks >= 90?No → try the next condition
  2. marks >= 75?Yes → grade = "A"
  3. Remaining elif / elseSkipped entirely
  4. print(...)Continues after the whole if-chain

Common mistake: conditions in the wrong order

If you test marks >= 40 first, a 95 would get a "C", because that is the first true condition. Put the most specific (highest) checks first. Similarly, a chain of separate if statements is not the same as if/elif: separate ifs are all checked, so several can run.

Nested conditions

You can put an if inside another. It works, but deep nesting quickly becomes hard to read:

is_logged_in = True
role = "editor"

if is_logged_in:
    if role == "admin":
        print("Full access")
    else:
        print("Limited access")
else:
    print("Please log in")

Output

Limited access

Often you can flatten nesting with and, or by handling the "bad" case first. This style – called a guard clause – is common in professional code:

def access_level(is_logged_in, role):
    if not is_logged_in:
        return "Please log in"
    if role == "admin":
        return "Full access"
    return "Limited access"

print(access_level(True, "admin"))
print(access_level(False, "admin"))

Output

Full access
Please log in

(Functions are covered properly in chapter 9 – here just notice how flat and readable the logic becomes.)

The conditional expression (one-line if)

When you only need to pick between two values, write it on one line: value_if_true if condition else value_if_false.

age = 16
status = "adult" if age >= 18 else "minor"
print(status)

items = 1
print(f"{items} item{'s' if items != 1 else ''} in cart")

Output

minor
1 item in cart

Keep it for simple choices. If you find yourself nesting conditional expressions, go back to a normal if statement.

Truthy conditions

Because every value is truthy or falsy, you can write natural checks without comparing to True, 0 or "":

cart = []
coupon = "SAVE10"

if not cart:
    print("Your cart is empty")
if coupon:
    print(f"Coupon {coupon} applied")

Output

Your cart is empty
Coupon SAVE10 applied

Write if cart: rather than if len(cart) > 0: and if is_valid: rather than if is_valid == True:. Both are shorter and more "Pythonic".

An empty block: pass

A block can't be empty. While you are still writing code, use pass as a placeholder:

score = 0
if score > 100:
    pass   # TODO: award a badge
print("done")

Output

done

Real example: electricity bill

Slab-based pricing is a perfect if/elif problem. First 100 units cost ₹3, the next 100 cost ₹5, everything above 200 costs ₹8:

units = 260

if units <= 100:
    bill = units * 3
elif units <= 200:
    bill = 100 * 3 + (units - 100) * 5
else:
    bill = 100 * 3 + 100 * 5 + (units - 200) * 8

print(f"{units} units → ₹{bill}")

Output

260 units → ₹1280

Practice

Try it yourself

  1. Given three numbers, print the largest without using max().

    Show solution
    a, b, c = 14, 31, 9
    if a >= b and a >= c:
        largest = a
    elif b >= c:
        largest = b
    else:
        largest = c
    print(largest)

    Output

    31
  2. Classify a BMI value: below 18.5 underweight, below 25 normal, below 30 overweight, otherwise obese.

    Show solution
    weight, height = 68, 1.72
    bmi = weight / height ** 2
    if bmi < 18.5:
        label = "underweight"
    elif bmi < 25:
        label = "normal"
    elif bmi < 30:
        label = "overweight"
    else:
        label = "obese"
    print(f"BMI {bmi:.1f}: {label}")

    Output

    BMI 23.0: normal

Quick check

In an if/elif chain, how many blocks can run?

At most one – the first whose condition is true (or the else block if none are).

Rewrite as one line: if x > 0: sign = "+" else: sign = "-"

sign = "+" if x > 0 else "-"

What does pass do?

Nothing. It is a placeholder for a block that must exist but has no code yet.

Summary

  • if runs a block when its condition is truthy; else handles the rest.
  • elif chains are checked top to bottom; only the first match runs.
  • Prefer guard clauses and and over deep nesting.
  • a if condition else b picks between two values in one line.

Finished this lesson?

Mark it complete to track your progress, then carry on with the next lesson.

Next lesson

Search LearnFrenzy

Esc

Quick links