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}")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)}")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")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)")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,eliforelsegives aSyntaxError. - Using
=instead of==inside a condition. - Writing
if city == "Chennai" or "Madurai":. The right side,"Madurai", is a non-empty string and always true. Writeif 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.
