Python If...Else
Learn how Python if, elif, and else statements work — with syntax, comparison operators, logical operators, nested conditions, and the ternary shorthand.
Conditional statements let a Python program choose between different paths of execution depending on whether a condition is true or false. This chapter covers every form of Python conditional: if, if-else, if-elif-else, nested if, and the one-line shorthand — along with the comparison and logical operators that make conditions work.
The if Statement
The if statement is the simplest conditional. The indented block runs only when the condition evaluates to True.
if condition:
# code that runs when condition is TrueExample
Python uses indentation (4 spaces by convention) to define the block — there are no curly braces. If the condition is False, the block is simply skipped.
Comparison Operators
Conditions are built from expressions that compare two values. Each expression produces a Python boolean — True or False.
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | Equal to | 5 == 5 | True |
!= | Not equal to | 5 != 3 | True |
> | Greater than | 5 > 3 | True |
< | Less than | 5 < 3 | False |
>= | Greater than or equal to | 5 >= 5 | True |
<= | Less than or equal to | 4 <= 5 | True |
See Python Operators for the full operator reference including arithmetic and assignment operators.
Logical Operators
Logical operators combine multiple conditions into a single expression.
| Operator | Returns True when… | Example |
|---|---|---|
and | Both conditions are True | x > 0 and x < 10 |
or | At least one condition is True | x < 0 or x > 100 |
not | The condition is False | not logged_in |
Example — and
Example — or and not
day = "Saturday"
if day == "Saturday" or day == "Sunday":
print("It is the weekend")
logged_in = False
if not logged_in:
print("Please log in")The if-else Statement
Add an else clause to handle the case when the condition is False.
if condition:
# runs when condition is True
else:
# runs when condition is FalseExample
Only one of the two blocks will ever execute for a given run.
The if-elif-else Statement
Use elif (short for "else if") to test several conditions in sequence. Python checks them top to bottom and executes the first matching block. The else block at the end is a catch-all for when none of the conditions match.
if condition1:
# runs when condition1 is True
elif condition2:
# runs when condition2 is True and condition1 is False
elif condition3:
# runs when condition3 is True and the above are False
else:
# runs when none of the above are TrueYou can have as many elif clauses as you need, but only one if and at most one else.
Example — grade classification
Why order matters: once Python finds a True condition it stops checking. If you wrote score >= 60 first, a score of 95 would print "Grade: C" because 95 is also >= 60. Always put the most specific (strictest) condition first.
Nested if Statements
An if statement can appear inside the block of another if statement. This is called nesting and is useful when you need to apply a secondary test only after a primary one passes.
score = 85
if score >= 60:
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
else:
print("Grade: C")
else:
print("Grade: F")
# Output: Grade: BGotcha: deep nesting makes code hard to read. Prefer elif chains for flat comparisons, and consider extracting nested logic into a function when nesting exceeds two levels.
Truthiness and Falsy Values
Python treats many values as implicitly True or False without using a comparison operator. Values that are considered False in a boolean context are:
NoneFalse0(integer zero),0.0(float zero)""(empty string),[](empty list),{}(empty dict),()(empty tuple),set()(empty set)
Everything else is considered True. This lets you write concise guards:
name = "Alice"
if name:
print("Name is set") # prints because "Alice" is truthy
items = []
if not items:
print("The list is empty") # prints because [] is falsy
value = None
if value is None:
print("No value provided") # use 'is None' for explicit None checksUse is None / is not None (not == None) when testing for None specifically — it is the Python style convention and avoids accidental matches.
Short-Hand if (Ternary Expression)
Python's one-line conditional expression assigns one of two values based on a condition:
value = result_if_true if condition else result_if_falseExample
age = 20
status = "adult" if age >= 18 else "minor"
print(status)
# Output: adultThis is equivalent to:
if age >= 18:
status = "adult"
else:
status = "minor"Use the ternary form for simple value assignments. Avoid nesting it — a if c1 else b if c2 else c quickly becomes unreadable.
The pass Statement
Python requires at least one statement inside every block. If you want to define an if branch that intentionally does nothing (a placeholder during development), use pass:
x = 10
if x > 5:
pass # TODO: handle this case later
else:
print("x is 5 or less")pass is a no-op — it tells Python "this block is intentionally empty."
The Walrus Operator := (Python 3.8+)
The walrus operator assigns a value to a variable and tests it in the same expression. It is most useful when you need the tested value inside the if block:
numbers = [1, 2, 3, 4, 5]
if (n := len(numbers)) > 3:
print(f"List has {n} items, which is more than 3")
# Output: List has 5 items, which is more than 3Without :=, you would need a separate assignment line. The parentheses around n := len(numbers) are required here to avoid ambiguity.
Common Gotchas
Using = instead of ==
# Wrong — this is assignment, not comparison, and causes a SyntaxError in conditions
# if x = 5:
# Correct
if x == 5:
print("x is five")Forgetting the colon
Every if, elif, and else line must end with :. A missing colon produces a SyntaxError.
Inconsistent indentation
All statements in the same block must use exactly the same indentation. Mixing tabs and spaces causes an IndentationError. Stick to 4 spaces, which is the PEP 8 standard.
What to Use When
| Scenario | Best choice |
|---|---|
| One condition, single action | if |
| Two mutually exclusive paths | if-else |
| Three or more paths | if-elif-else |
| Secondary test inside a branch | Nested if |
| Simple value assignment | Ternary x if c else y |
| Multi-value equality checks (Python 3.10+) | match statement |
Practice
Once you understand conditionals, the natural next step is repeating code with Python while loops and Python for loops.