Lesson 6 of 12

Python Conditions (if, elif, else)

So far, every line of your programs has run every time. Real programs need to make choices: give a discount only to members, show “Out of stock” only when the count is zero, charge a different fee at night. You make these choices with Python conditions: if, elif and else. They use the comparisons and logical operators from Python Operators.

The if statement

An if statement has a condition, a colon and an indented block. The block runs only when the condition is true. If it is false, Python skips the block and carries on with the next line at the outer level.

cart_total = 1150

if cart_total >= 999:
    print("You get free delivery!")
    cart_total -= 50   # festival coupon for big orders

print(f"Amount to pay: ₹{cart_total}")
Output
You get free delivery!
Amount to pay: ₹1100

Try changing cart_total to 800 and run it again: the two indented lines are skipped and the amount stays ₹800. A block can never be empty. If you want to write the if now and fill it in later, put the keyword pass inside it, which means “do nothing”.

else and elif

Add else for what should happen when the condition is false. When there are more than two possibilities, add one or more elif (“else if”) branches between them. Python checks the conditions from top to bottom and runs only the first block whose condition is true; the rest are skipped, even if they would also be true.

def grade(marks):
    if marks >= 90:
        return "O (Outstanding)"
    elif marks >= 75:
        return "A"
    elif marks >= 60:
        return "B"
    elif marks >= 40:
        return "C"
    else:
        return "Fail"

for student, marks in [("Nila", 94), ("Vikram", 76), ("Sara", 58), ("Hari", 31)]:
    print(f"{student}: {marks} -> {grade(marks)}")
Output
Nila: 94 -> O (Outstanding)
Vikram: 76 -> A
Sara: 58 -> C
Hari: 31 -> Fail

The code is wrapped in a small function so it can be tested with several students; you will learn functions in Python Functions. Focus on the order of the branches. Because 94 matches marks >= 90 first, Python never checks the other branches. If you put marks >= 40 at the top, everyone who passed would get a C. Always order range checks from the most specific to the least.

Combining and nesting Python conditions

Use and, or and not to combine tests in one condition. You can also put an if inside another if, which is called nesting. Nesting is fine for one or two levels, but deep nesting is hard to read. Often you can flatten it by combining conditions with and.

age = 67
is_resident = True
ticket = 200

if age >= 60 and is_resident:
    ticket = ticket // 2
    print("Senior citizen concession applied")

print(f"Ticket: ₹{ticket}")

hour = 22
is_raining = True
if hour >= 21:
    if is_raining:
        print("Night fare plus rain surcharge")
    else:
        print("Night fare")
else:
    print("Normal fare")
Output
Senior citizen concession applied
Ticket: ₹100
Night fare plus rain surcharge

Truthiness in conditions

A condition does not have to be a comparison. Python treats empty strings, empty lists, 0 and None as false, and everything else as true. So if cart: means “if the cart list is not empty”, and if not name: means “if the name is missing or empty”. This short style is normal Python, as explained in Python Data Types.

Conditional expressions (one-line if)

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. For example, status = "Open" if 9 <= hour < 21 else "Closed". Use it for simple choices only. If you need elif or several statements, write a normal if block.

The match statement

Since Python 3.10, match compares one value against several patterns. For a beginner, think of it as a neat replacement for a long chain of elif value == …. Each case is checked in order. A | means “or”, and the special pattern case _: matches anything, like else.

hour = 20
status = "Open" if 9 <= hour < 21 else "Closed"
print("Shop is", status)

def delivery_days(state):
    match state:
        case "Tamil Nadu" | "Puducherry":
            return 1
        case "Kerala" | "Karnataka" | "Andhra Pradesh" | "Telangana":
            return 2
        case _:
            return 5

for state in ["Puducherry", "Kerala", "Assam"]:
    print(f"{state}: {delivery_days(state)} day(s)")
Output
Shop is Open
Puducherry: 1 day(s)
Kerala: 2 day(s)
Assam: 5 day(s)

Tip: match can do much more than compare simple values: it can unpack lists and dictionaries and check their shape. The Python tutorial’s section on match statements shows these advanced patterns when you are ready.

Common mistakes with Python conditions

  • Forgetting the colon at the end of if, elif or else gives a SyntaxError.
  • Using = instead of == inside a condition.
  • Writing if city == "Chennai" or "Madurai":. The right side, "Madurai", is a non-empty string and always true. Write if city == "Chennai" or city == "Madurai":, or better, if city in ("Chennai", "Madurai"):.
  • Inconsistent indentation inside a block, which gives an IndentationError.

Watch out: Comparing user text is case-sensitive: "chennai" == "Chennai" is False. Clean input first with .strip().lower() and compare with lower-case values.

Further reading

Key takeaways

  • if runs an indented block only when its condition is true.
  • elif adds more branches and else catches everything else; only the first true branch runs.
  • Combine tests with and, or, not, and keep nesting shallow.
  • Use a if condition else b for a simple choice between two values.
  • match/case (Python 3.10+) neatly replaces long chains of equality checks.

Quick quiz

Check what you learned – pick an answer.

1. marks = 85. Which branch runs? if marks >= 40: ... elif marks >= 80: ...

2. What does "Even" if 7 % 2 == 0 else "Odd" evaluate to?

3. In a match statement, what does case _: do?

Practice exercise

Write code that takes units = 260 (electricity used in a month) and prints the bill using these simple slabs: up to 100 units free, 101–200 units at ₹2.25 per unit, above 200 units at ₹4.50 per unit for every unit beyond 200.

Show a hint

Use if/elif/else on units. For 260 units: the first 100 are free, the next 100 cost 2.25 each, the last 60 cost 4.50 each.

Show the solution
units = 260

if units <= 100:
    bill = 0
elif units <= 200:
    bill = (units - 100) * 2.25
else:
    bill = 100 * 2.25 + (units - 200) * 4.50

print(f"Units: {units}, bill: ₹{bill:.2f}")

Progress is saved in this browser only.