Conditionals introduction

Conditionals

Every interesting program needs to make decisions. Python's if statement runs a block of code only when a condition is true:

age = 20
if age >= 18:
    print("adult")

if / elif / else

Chain conditions with elif ("else if"), and catch everything else with else:

def describe(temp):
    if temp < 0:
        return "freezing"
    elif temp < 20:
        return "cold"
    elif temp < 30:
        return "warm"
    else:
        return "hot"

Python checks each condition top to bottom and runs the first block whose condition is true — the rest are skipped entirely, even if they'd also be true. That ordering matters: for temp = -5, the very first condition (temp < 0) already matches, so elif temp < 20 never even gets evaluated.

Indentation is the block

Unlike many languages, Python doesn't use {} to mark a block — indentation is the block. Everything indented under an if (usually 4 spaces) belongs to it:

if x > 0:
    print("positive")
    print("still inside the if")
print("outside the if — always runs")

No braces, no semicolons

Each statement is its own line, and the if/elif/else line always ends with a colon :. That colon is easy to forget when you're coming from another language — Python won't run without it.

Next: the comparison and boolean operators that go inside these conditions.