Python Programming · Lesson 4 of 15 · Updated ·
Conditions in Python — if, elif, else and Nested Conditions
Programs need to make decisions: if the marks are 90 or more, print Grade A. That's what if does.
1. if, elif, else
marks = 72
if marks >= 90:
print("Grade A")
elif marks >= 60:
print("Grade B")
else:
print("Grade C")
Grade B
- Python checks the conditions top to bottom and runs the first block whose condition is True.
elifandelseare optional. You can have manyelifs.- Every block ends with a colon
:and is indented.
Order matters. If you check
marks >= 60first, a student with 95 gets "Grade B" because that condition is also true.
2. Combining conditions
age = 22
cgpa = 7.8
backlogs = 0
if age <= 25 and cgpa >= 7 and backlogs == 0:
print("Eligible for the drive")
else:
print("Not eligible")
Eligible for the drive
Python also allows chained comparisons: if 18 <= age <= 25: reads just like maths.
3. Nested conditions
An if inside another if:
n = -8
if n >= 0:
print("Non-negative")
else:
if n % 2 == 0:
print("Negative even")
else:
print("Negative odd")
Negative even
Prefer elif or and when they make the code flatter and easier to read.
4. The conditional expression (one-line if)
n = 7
result = "even" if n % 2 == 0 else "odd"
print(result)
odd
5. Checking membership and empty values
city = "Jaipur"
if city in ["Jaipur", "Udaipur", "Jodhpur"]:
print("Rajasthan")
name = ""
if not name:
print("Name is empty")
Rajasthan
Name is empty
6. match-case (Python 3.10+)
For many fixed values, match is cleaner than a long elif chain:
day = 6
match day:
case 6 | 7:
print("Weekend")
case 1 | 2 | 3 | 4 | 5:
print("Weekday")
case _:
print("Invalid day")
Weekend
case _ is the default (like else).
Example: leap year
year = 2024
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
print(year, "is a leap year")
else:
print(year, "is not a leap year")
2024 is a leap year
Common mistakes
- Writing
=instead of==in a condition (SyntaxError). - Forgetting the colon or the indentation.
- Putting the broader condition before the stricter one.
Quick recap
if→elif→else; the first True branch runs, only one.- Combine with
and,or,not; chained comparisons like18 <= age <= 25. - One-line form:
a if condition else b. inchecks membership; empty values are falsy.