Conditionals (if/elif/else) in Python
Conditionals let a program make decisions and run different code depending on whether an expression is True or False. Python uses the if, elif, and else keywords to build these decisions.
The Basic if Statement
An if statement runs a block of code only when its condition evaluates to True. As explained on the Syntax & Indentation page, Python uses indentation rather than braces to mark where a block starts and ends, so every line inside the if block must be indented consistently, typically by 4 spaces.
age = 20
if age >= 18:
print("You are an adult")
print("You can vote")
print("This line always runs")
if/elif/else Chains
When there are more than two possible outcomes, elif (short for "else if") lets you test additional conditions in order. Python checks each condition from top to bottom and runs the first block whose condition is True; if none match, the else block runs.
score = 76
if score >= 90:
grade = "A"
elif score >= 75:
grade = "B"
elif score >= 60:
grade = "C"
else:
grade = "F"
print("Grade:", grade) # Grade: B
Note: Only one block in the chain ever runs. Once a condition matches, Python skips every remaining elif and else in that chain.
Truthy and Falsy Values
An if condition does not have to be a strict True / False comparison — any value can be tested directly, because every Python value is considered either "truthy" or "falsy".
| Falsy values | Truthy values |
|---|---|
0, 0.0 | any non-zero number |
"" (empty string) | any non-empty string |
[], (), {}, set() | any non-empty list, tuple, dict, or set |
| None | most other objects |
cart = []
if cart:
print("You have items in your cart")
else:
print("Your cart is empty") # this runs, since [] is falsy
The Ternary (Conditional) Expression
For simple two-way decisions, Python offers a compact one-line form called a conditional expression, sometimes called a ternary operator. It has the form value_if_true if condition else value_if_false.
age = 16
status = "adult" if age >= 18 else "minor"
print(status) # minor
# equivalent to the longer form:
# if age >= 18:
# status = "adult"
# else:
# status = "minor"
Nested Conditionals
An if statement can be placed inside another if statement, allowing you to check additional conditions only once an outer condition is satisfied.
age = 25
has_id = True
if age >= 18:
if has_id:
print("Entry allowed")
else:
print("ID required for entry")
else:
print("Too young for entry")
Combining Conditions with and / or
As covered on the Operators page, the logical operators and, or, and not let you combine multiple conditions into a single expression, often avoiding the need for nested if statements.
age = 25
has_id = True
# combined with 'and' instead of nesting
if age >= 18 and has_id:
print("Entry allowed")
else:
print("Entry denied")
is_weekend = True
is_holiday = False
if is_weekend or is_holiday:
print("No work today")