Python Conditional Statements (if, elif, else)
Conditional statements branch execution dynamically. The conditions are evaluated sequentially from top to bottom; once the first True condition executes, all subsequent elif and else branches are skipped:
# Grading system based on marks:
marks = 82
if marks >= 90:
print("Grade: A+ (Outstanding!) ๐")
elif marks >= 75:
print("Grade: A (Very Good!) โจ")
elif marks >= 50:
print("Grade: B (Pass) ๐")
else:
print("Grade: Fail โ")
- Python tests
marks >= 90(82 >= 90 is False) -> skips. - Python tests
marks >= 75(82 >= 75 is True) -> printsGrade: A (Very Good!) โจ. - All remaining branches (
elif marks >= 50andelse) are immediately bypassed!
Deeply nested if statements make code difficult to read. Professional developers use Guard Clauses (early returns) to keep logic flat and clean:
def check_user_access(is_logged_in, has_permission, is_banned):
# Guard Clauses (Early Exits):
if not is_logged_in:
return "Please log in first."
if is_banned:
return "Account is banned!"
if not has_permission:
return "Access denied."
return "Welcome to Admin Dashboard! โ
"
print(check_user_access(True, True, False))
Guard clauses handle failure/invalid conditions early and return immediately, keeping the "happy path" un-indented and crystal clear.
Python provides an inline ternary conditional expression with the syntax: value_if_true if condition else value_if_false:
age = 20
status = "Adult" if age >= 18 else "Minor"
print("Status:", status)
# Dynamic fee calculation:
is_weekend = True
entry_fee = 25 if is_weekend else 15
print(f"Entry Fee: ${entry_fee}")
Ternary expressions are perfect for simple variable assignments based on a single condition.
Python 3.10 introduced match-case, replacing clumsy switch-case statements with powerful structural pattern matching and OR patterns (|):
http_status = 404
match http_status:
case 200:
print("200 OK: Request succeeded! โ
")
case 401 | 403:
print("Auth Error: Access forbidden.")
case 404:
print("404 Not Found: Page does not exist! โ")
case _:
print("Other Server Status Code")
case 401 | 403:matches either 401 OR 403.case _:acts as the wildcard fallback (equivalent todefault:in C/Java).
If you use multiple if statements sequentially, Python evaluates EVERY single condition independently, even after finding a match. Using elif ensures that once the first True branch executes, all subsequent checks are skipped.
Check if a year is a Leap Year (divisible by 4 and not divisible by 100, or divisible by 400).
year = 2024
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(f"โ
{year} is a Leap Year!")
else:
print(f"โ {year} is NOT a Leap Year.")
Q Does Python have a traditional switch-case statement?
Python 3.10 introduced match-case (Structural Pattern Matching) which replaces switch-case and supports deep object destructuring and guard conditions.
Q What is the difference between pass and continue?
pass is a no-op placeholder that allows execution to proceed to the next line. continue is used exclusively inside loops to skip the remainder of the current loop iteration and jump to the next cycle.
Q Can ternary operators be chained in Python?
Yes: x = "A" if score >= 90 else ("B" if score >= 80 else "C"). However, if chaining exceeds two levels, use standard if-elif-else for better readability.