A conditional statement (also called an if statement) executes different blocks of code depending on boolean conditions. The syntax is if condition: (required), followed by zero or more elif condition: clauses, and an optional else: clause. Python evaluates conditions top-to-bottom and executes the first block whose condition is truthy, skipping the rest.
Python's conditional expressions (ternary operator) allow inline conditionals: result = x if condition else y. This is useful for simple value selection but should not be nested for readability. The match statement (Python 3.10+, PEP 634) provides structural pattern matching — a more powerful alternative to long if/elif chains for matching against complex data structures.
Conditions in Python leverage truthiness: any object can be tested in a boolean context. Empty collections, zero, None, and False are falsy; everything else is truthy. The logical operators and, or, and not combine conditions and short-circuit: x and y returns x if x is falsy, otherwise y. This enables idioms like name = user_name or "Anonymous", which uses or as a default-value operator.
Related terms: Boolean, Match Statement, Indentation
Discussed in:
- Chapter 4: Control Flow — Conditional Statements