Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The if statement is a fundamental control flow construct in Python used for conditional execution. It evaluates an expression in a boolean context and executes an associated suite (an indented block of code) strictly if the expression resolves to a truthy value.

Syntax

if expression_1:
    # suite_1
elif expression_2:
    # suite_2
else:
    # suite_3

Structural Components

  • if clause: The mandatory starting point. It contains the primary expression to be evaluated.
  • elif (else if) clause: Optional. You can chain multiple elif clauses. They are evaluated sequentially only if all preceding expressions evaluated to falsy values.
  • else clause: Optional. It must be the final clause in the structure. It acts as a catch-all, executing its suite if and only if all preceding if and elif expressions resolve to falsy values.
  • Colon (:): Mandatory. It acts as a syntactic delimiter separating the expression from the suite.
  • Indentation: Python enforces lexical structure via whitespace. The suite following any conditional clause must be uniformly indented (typically 4 spaces) relative to the keyword.

Evaluation Mechanics

  1. Truth Value Testing: Python does not require expressions to be strictly of type bool. When an expression is evaluated, Python implicitly checks its “truthiness” using the built-in bool() function.
    • Falsy values: False, None, numeric zeros (0, 0.0, 0j), and empty collections/sequences ("", [], {}, (), set()).
    • Truthy values: Any value not explicitly defined as falsy.
  2. Short-Circuiting: The if...elif...else chain evaluates top-down. The moment an expression evaluates to a truthy value, its corresponding suite is executed, and the entire control structure terminates. Subsequent elif or else blocks are completely bypassed and their expressions are not evaluated.
  3. Variable Scope: Unlike C-family languages, Python if statements do not create a new local scope. Variables bound or modified within an if, elif, or else suite bleed into the enclosing scope and remain accessible after the control structure terminates, provided that specific suite was executed.

Conditional Expressions (Ternary Operator)

Python also supports an inline conditional expression, which evaluates to one of two values based on a boolean expression. It is an expression, not a statement, meaning it returns a value and can be assigned to a variable.
result = value_if_true if expression else value_if_false
In this construct, expression is evaluated first. If truthy, value_if_true is evaluated and returned. If falsy, value_if_false is evaluated and returned.
Master Python with Deep Grasping Methodology!Learn More