elif — Intermediate Examples
Short for 'else if'; adds another condition to an if chain
elif vs dictionary dispatch
Comparing elif chains to dictionary-based dispatch.
python
# elif chain def describe_http(code): if code == 200: return "OK" elif code == 301: return "Moved Permanently" elif code == 404: return "Not Found" elif code == 500: return "Internal Server Error" else: return f"Unknown ({code})" # Dictionary dispatch (often cleaner) HTTP_CODES = { 200: "OK", 301: "Moved Permanently", 404: "Not Found", 500: "Internal Server Error", } def describe_http_dict(code): return HTTP_CODES.get(code, f"Unknown ({code})") for code in [200, 404, 418]: print(f"{code}: {describe_http(code)} | {describe_http_dict(code)}")
Expected Output
200: OK | OK 404: Not Found | Not Found 418: Unknown (418) | Unknown (418)
Long elif chains can often be replaced with dictionary lookups, which are cleaner and O(1) vs O(n) for the chain.
elif with complex conditions
Combining elif with logical operators.
python
def classify_bmi(bmi): if bmi < 0: return "Invalid" elif bmi < 18.5: return "Underweight" elif 18.5 <= bmi < 25: return "Normal" elif 25 <= bmi < 30: return "Overweight" else: return "Obese" test_values = [17.5, 22.0, 27.3, 32.1] for bmi in test_values: print(f"BMI {bmi}: {classify_bmi(bmi)}")
elif conditions are tested in order, so each branch can assume all previous conditions were False.
Want to try these examples interactively?
Open Intermediate Playground