Andromeda
Note

if Statements (Python)

Definition

Control structures used to execute specific blocks of code based on the result of one or more conditional tests.

Why It Matters

They are the “decision-making” foundation of all software, allowing code to respond dynamically to different conditions. Mastering conditional logic is the first step in moving from static scripts to intelligent, adaptive programs that can handle real-world complexity.

Core Concepts

  • The if Clause: Consists of the if keyword, a condition, a colon, and an indented block of code.
  • if-else: A binary branch. If the test passes, the if block runs; otherwise, the else block runs.
  • if-elif-else Chain:
    • A multi-path branch where at most one block will execute.
    • Python stops checking conditions as soon as it finds one that is True.
    • Order Matters: If multiple conditions are true, only the first one in the chain runs. This can lead to logical bugs if specific conditions are placed after general ones.
  • Boolean Context: Python evaluates conditions in a Boolean context. True values are processed, while False values cause the block to be skipped.
age = 18

if age < 13:
    print("Child")
elif age < 20:
    print("Teenager")
else:
    print("Adult")

Connected Concepts