Topic 40 of 64
If, Elif, Else Conditions
Overview
Python's if/elif/else uses indentation (not braces) as block delimiters. The elif chain is Python's equivalent of else-if. Mastering conditional logic is the most fundamental skill in any programming interview.
Syntax
python
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(f"Grade: {grade}") # Grade: B
# One-liner ternary (conditional expression)
result = "pass" if score >= 60 else "fail"Common Pitfalls
- Python uses strict indentation (4 spaces) — mixing tabs and spaces causes IndentationError.
- There is no 'switch' statement in Python < 3.10. Use if/elif chains or dicts for dispatch. Python 3.10+ has 'match/case'.
- Interview tip: For multiple equality checks, prefer a dict dispatch table over long elif chains for cleaner, more extensible code.
Real-World Example
HTTP status code handler function
example
python
def handle_status(code: int) -> str:
if 200 <= code < 300:
return "Success"
elif 300 <= code < 400:
return "Redirect"
elif 400 <= code < 500:
return "Client Error"
elif 500 <= code < 600:
return "Server Error"
else:
return "Unknown status"
print(handle_status(404)) # Client Error
print(handle_status(200)) # Success