If-Else
How Python makes decisions — running one block of code instead of another based on a condition.
If Statement
An if statement tests a condition. If it evaluates to True, the indented block underneath runs; otherwise Python skips straight past it.
age = 20
if age >= 18:
print("You can vote.")
You can vote.
Else Statement
An else block runs only when the if condition (and every elif above it) turned out False. It can't have its own condition — it's the catch-all.
age = 15
if age >= 18:
print("You can vote.")
else:
print("Not old enough yet.")
Not old enough yet.
Elif Statement
When there's more than one condition to check, elif ("else if") chains additional tests between the if and the else. Python checks them top to bottom and runs the first block whose condition is True — the rest are skipped, even if they'd also be true.
age = 19
if age < 13:
print("Child")
elif age < 20:
print("Teenager")
else:
print("Adult")
Teenager
if statements can also be nested inside each other for more layered decisions:
age = 25
height = 160
if age >= 18:
if height > 180:
print("Eligible to race.")
else:
print("Old enough, but not tall enough.")
else:
print("Too young to race.")
Old enough, but not tall enough.