if, elif & else

Python · Lesson 13 of 56 6 min read Updated

Programs become useful when they can react differently to different situations. Free delivery above ₹499. A pass or fail result. A different greeting in the morning and in the evening. In Python, the if statement makes these decisions.

In this lesson you will write if, else and elif blocks, choose between many options in the right order, write short one-line conditions, and avoid the logic mistakes that give wrong answers without any error message.

The if statement

An if statement runs a block of code only when a condition is true. The condition is any expression that gives a truthy or falsy value, usually a comparison from Booleans & Operators.

PythonRun it yourself
cart_total = 620

if cart_total >= 499:
    print("You get free delivery!")
    print("Your order ships today.")

print("Thank you for shopping.")
Output
You get free delivery!
Your order ships today.
Thank you for shopping.

The line starts with if, then the condition, then a colon. The indented lines below it are the block. The last line is not indented, so it runs whatever the condition is. Change cart_total to 300 and run it again to see the difference.

else: the other path

Add else to run a different block when the condition is false. Exactly one of the two blocks always runs.

PythonRun it yourself
marks = 28
pass_mark = 33

if marks >= pass_mark:
    print("Result: Pass")
else:
    short = pass_mark - marks
    print(f"Result: Fail, {short} marks short")
Output
Result: Fail, 5 marks short

else has no condition of its own and ends with a colon. It lines up with its if, not with the code inside the block.

elif: many choices

When there are more than two possibilities, add elif (short for "else if") branches. Python checks the conditions from top to bottom and runs the first block whose condition is true. All the rest are skipped.

PythonRun it yourself
percentage = 76

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

print("Grade:", grade)
Output
Grade: A

76 is not 90 or more, so the first branch is skipped. It is 75 or more, so grade becomes "A" and Python jumps past the whole chain. It never checks >= 60, even though that is also true. That is why the order of the branches matters: check the strictest condition first.

Combining conditions

Use and, or, not and in to express rules that depend on more than one value:

PythonRun it yourself
age = 67
is_member = False
city = "Pune"

if city in ("Pune", "Mumbai") and (is_member or age >= 60):
    print("Free entry to the book fair")
elif age < 5:
    print("Children under 5 enter free")
else:
    print("Entry ticket: ₹50")
Output
Free entry to the book fair

The brackets matter here. Without them, and would be checked before or, and every member from any city would get in free. A long condition is also harder to read, so you can give parts of it a name first: is_local = city in ("Pune", "Mumbai"), then if is_local and (is_member or age >= 60):.

Nested if statements

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

PythonRun it yourself
has_account = True
balance = 1500
amount = 2000

if has_account:
    if balance >= amount:
        print("Payment successful")
    else:
        print(f"Insufficient balance: you need ₹{amount - balance} more")
else:
    print("Please create an account first")
Output
Insufficient balance: you need ₹500 more

Nesting is fine for one or two levels. Deeper than that, the code drifts to the right and becomes hard to follow. Often you can flatten it with and or with an elif chain.

Conditional expressions

When you only need to choose between two values, a conditional expression fits on one line: value_if_true if condition else value_if_false.

PythonRun it yourself
stock = 0
label = "In stock" if stock > 0 else "Out of stock"
print(label)

items = 1
print(f"You have {items} {'item' if items == 1 else 'items'} in your cart")
Output
Out of stock
You have 1 item in your cart

Use it for simple choices like these. If either side needs more than a short value, a normal if and else block is easier to read.

Truthiness and pass

Because empty values are falsy, you can test collections and strings directly. if cart: means "if the cart has anything in it", and if not name: means "if the name is empty". For None, be explicit and write if result is None:.

Sometimes you need a block that does nothing yet, for example while you are still planning the code. A block cannot be empty, so write pass, a statement that does nothing.

When you have one value to compare against many fixed options, or data with a particular shape, the match statement can be a cleaner choice. You will learn it in match Statements.

Common mistakes

  • Branches in the wrong order. If percentage >= 33 came first, everyone who passed would get a "C". Put the strictest test first.
  • Separate ifs instead of elif. Several independent if statements can all run. Use elif when only one branch should run.
  • Writing if is_member == True:. Just write if is_member:. It is shorter and works the same way.
  • Forgetting the colon or indentation. if, elif and else lines all end with :, and their blocks must be indented.

Key points

  • if condition: runs its indented block only when the condition is truthy.
  • else: runs when no earlier condition was true.
  • elif adds more branches; only the first true branch runs, so order matters.
  • Combine conditions with and, or, not and in; name long conditions to keep them readable.
  • a if condition else b chooses between two values in one line.
  • Empty values are falsy, so if items: checks that a list is not empty; pass fills an empty block.

Exercise

Write a program for an electricity bill in Rohtak. The first 100 units cost ₹3 each, units 101 to 300 cost ₹5 each, and every unit above 300 costs ₹7. Set units = 350 and print the total bill. Then add a line that prints "High usage" if the bill is more than ₹1,500, otherwise "Normal usage", using a conditional expression.

Show solution
Python
units = 350

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

print(f"Bill for {units} units: ₹{bill}")
print("High usage" if bill > 1500 else "Normal usage")
Output
Bill for 350 units: ₹1650
High usage

The elif chain picks exactly one formula, checking the smallest slab first. Each formula adds the full cost of the lower slabs to the cost of the units in the current slab.

Quick Quiz

1. In an if/elif/else chain, how many blocks run?

2. What does this print? x = 0 then print("yes" if x else "no")

3. Which keyword fills a block that should do nothing for now?

4. With marks = 95, which order of conditions gives the grade "A+"?

Learn Python with a mentor

Free lessons get you started. Our Python Programming training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call