Conditionals
Every program eventually needs to make a decision — charge sales tax or not, show an error or not, sort someone into one category instead of another. if is how Python does that.
if, elif, and else
Python checks each condition top to bottom and runs the first block whose condition is true, skipping the rest. else catches anything that didn't match:
score = 82
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print(grade)
B
82 fails the first check (it's not 90 or above), so Python moves to the next line. It passes score >= 80, sets grade to "B", and — this is the important part — never even looks at the remaining elif and else lines. Once one branch runs, the rest are skipped.
Combining conditions with and / or
and requires both sides to be true; or only needs one:
age = 20
has_ticket = True
if age >= 18 and has_ticket:
print("Welcome in")
else:
print("Not allowed")
Welcome in
Conditions can depend on more than one variable
temperature = 15
is_raining = True
if temperature < 10:
print("Wear a coat")
elif is_raining:
print("Bring an umbrella")
else:
print("Enjoy the weather")
Bring an umbrella
15 isn't below 10, so the first branch is skipped, and Python falls through to check is_raining, which is True.
A shorter form for simple cases
When a condition only decides between two values, you can write it on one line instead of spreading it across four:
age = 16 status = "adult" if age >= 18 else "minor" print(status)
minor
if, elif, or else isn't just for readability — it's how Python knows which lines belong to that branch. Every line in a block needs the same indentation, and mixing tabs with spaces (or just being inconsistent) will raise an IndentationError before your code even runs.