If / Elif / Else Logic/shaare/i3YPdw
If / Elif / Else Logic
Control the flow of scripts based on conditions using if, elif, and else.
The if Statement
An if statement executes a block of code only if a condition is True.
- Syntax:
if <condition>:followed by an indented block - Comparison operators:
==,!=,<,>,<=,>=,in - Combine conditions with
and,or,not
server_status = "running"
if server_status == "running":
print("Service is active.")
Truthiness
Python treats many values as truthy or falsy in conditionals.
- Falsy:
False,None,0,0.0,'',[],{} - Truthy: non-zero numbers, non-empty sequences/collections
servers = ["web01", "web02"]
error_message = ""
default_config = {}
if servers:
print(f"Processing {len(servers)} servers.")
if error_message:
print("Something went wrong:", error_message)
if not default_config:
print("Default config not available, please provide the configuration values.")
The else statement
Use else to execute code when the if condition is false.
cpu_usage = 85.0
if cpu_usage > 90.0:
print("ALERT: High CPU Usage")
else:
print("CPU Usage is normal.")
The elif statement
Chain multiple checks; the first true block runs.
http_status = 503
if http_status == 200:
print("Status OK")
elif http_status == 404:
print("Resource not found")
elif http_status >= 500:
print("Server error (5xx)")
else:
print("Another status:", http_status)
Guard Clauses
Handle edge cases at the top of functions to avoid deep nesting of if conditions.
def process_data_guarded(data):
if not data:
print("No data provided")
elif not isinstance(data, list):
print(f"Invalid value type for 'data'. Provided {type(data)}; Required: list")
else:
print(f"Processing {len(data)} items...")
print("Processed")
process_data_guarded(None)
process_data_guarded([])
process_data_guarded("abc")
process_data_guarded(10)
process_data_guarded([1, 2, 3])
(97)