Delete Set public Set private Add tags Delete tags
  Add tag   Cancel
  Delete tag   Cancel
  • • DevOps notes •
  •  
  • AI
  • Tags
  • Login

If / Elif / Else Logic/shaare/i3YPdw

  • python
  • python

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])
2 months ago Permalink
cluster icon
  • Dictionaries : Dictionaries (dict) Dictionaries are mutable, insertion-ordered collections of key-value pairs. Keys must be unique and immutable; values can be of an...
  • Signaling Errors: The raise Statement : Signaling Errors: The raise Statement Functions sometimes encounter states they cannot handle and must signal failure clearly. Using raise triggers...
  • Python Modules and the import System : Python Modules and the import System What is a Module? A module in Python corresponds directly to a single file containing Python code. The module's ...
  • Working with YAML files : Working with YAML files YAML (“YAML Ain’t Markup Language”) focuses on human readability. Indentation replaces braces and brackets, comments are allo...
  • Typing : Introduction Python is a dynamically typed language, meaning you can assign values to variables without declaring their types, and type checking happ...


(97)
Filter untagged links
Fold Fold all Expand Expand all Are you sure you want to delete this link? Are you sure you want to delete this tag? The personal, minimalist, super-fast, database free, bookmarking service by the Shaarli community