elif — Intermediate Playground
Short for 'else if'; adds another condition to an if chain
Python Playground
# 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)}")
Output
Click "Run" to execute your code
Long elif chains can often be replaced with dictionary lookups, which are cleaner and O(1) vs O(n) for the chain.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?