Supprimer Rendre public Rendre privé Add tags Delete tags
  Ajouter un tag   Annuler
  Supprimer le tag   Annuler
  • • DevOps notes •
  •  
  • AI
  • Tags
  • Connexion

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])
3 months ago Permalien
cluster icon
  • Tuples, sets : Tuples (tuple) Tuples are ordered, immutable sequences defined with parentheses (). Once created, their contents cannot be changed. Characteristics 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...
  • Working with CSV files : Working with CSV files CSV (Comma Separated Values) is a plain-text tabular format where each line is a row and fields are delimited (commonly by com...
  • Logging to Files : Logging to Files Basic File Logging with FileHandler Use logging.FileHandler to write log records to a file. mode='a' (append) preserves existing log...
  • Handling Errors and Status Codes : Handling Errors and Status Codes HTTP status codes communicate the outcome of an API request, and handling them correctly is key to robust automation...


(110)
Filtrer par liens sans tag
Replier Replier tout Déplier Déplier tout Êtes-vous sûr de vouloir supprimer ce lien ? Êtes-vous sûr de vouloir supprimer ce tag ? Le gestionnaire de marque-pages personnel, minimaliste, et sans base de données par la communauté Shaarli