Almost every useful program needs to make decisions — show a discount only if a cart total is high enough, print a different greeting depending on the time of day, or reject a form if a required field is empty. In Python, that decision-making is handled by the if, elif, and else statements, which run a block of code only when a given condition is true.
Unlike many other languages, Python doesn't use curly braces to mark these blocks — it uses indentation, which is why getting comfortable with Python's whitespace rules early on matters so much for conditionals specifically.
Basic if Statement
age = 20
if age >= 18:
print("You are an adult.")
Output:
You are an adult.
The colon : at the end of the if line is required, and everything indented underneath it (by convention, 4 spaces) is the block that runs only when the condition is True. If the condition is False, the indented block is simply skipped.
Adding else: A Fallback Branch
age = 15
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
Output:
You are a minor.
Chaining Conditions with elif
When you have more than two possible outcomes, elif ("else if") lets you check additional conditions in order. Python checks each condition from top to bottom and runs the first one that's true — the rest are skipped entirely, even if they would also be true.
score = 72
if score >= 90:
grade = "A"
elif score >= 75:
grade = "B"
elif score >= 60:
grade = "C"
else:
grade = "F"
print(f"Your grade is {grade}")
Output:
Your grade is C
Even though score = 72 also technically satisfies "greater than or equal to 0," only the elif score >= 60 branch runs, because it's the first condition (reading top-down) that evaluates to true. Order matters — if you'd written the conditions from lowest to highest instead, every score would incorrectly match the first (lowest) branch.
Nested if Statements
You can put an if statement inside another one when a decision depends on more than one independent check. This is called nesting, and each level needs its own additional indentation.
has_ticket = True
age = 16
if has_ticket:
if age >= 18:
print("Entry allowed, no restrictions.")
else:
print("Entry allowed, but with a guardian.")
else:
print("Entry denied — no ticket.")
Output:
Entry allowed, but with a guardian.
Nesting works, but more than two or three levels deep quickly becomes hard to read. In that situation, it's often cleaner to combine conditions with and/or in a single if line instead — for example, if has_ticket and age >= 18: — which brings you back to understanding how Python evaluates mixed operators correctly.
A Quick Note on Comparison
The conditions after if/elif are typically built from comparison operators (==, !=, <, >, <=, >=) or boolean combinations of them. Python also lets you use non-boolean values directly as conditions — for instance if my_list: checks whether the list is non-empty — which is covered in more depth in the guide to truthy and falsy values.
