W3docs

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 True

Example

python— editable, runs on the server

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 booleanTrue or False.

OperatorMeaningExampleResult
==Equal to5 == 5True
!=Not equal to5 != 3True
>Greater than5 > 3True
<Less than5 < 3False
>=Greater than or equal to5 >= 5True
<=Less than or equal to4 <= 5True

See Python Operators for the full operator reference including arithmetic and assignment operators.

Logical Operators

Logical operators combine multiple conditions into a single expression.

OperatorReturns True when…Example
andBoth conditions are Truex > 0 and x < 10
orAt least one condition is Truex < 0 or x > 100
notThe condition is Falsenot logged_in

Example — and

python— editable, runs on the server

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 False

Example

python— editable, runs on the server

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 True

You can have as many elif clauses as you need, but only one if and at most one else.

Example — grade classification

python— editable, runs on the server

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: B

Gotcha: 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:

  • None
  • False
  • 0 (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 checks

Use 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_false

Example

age = 20
status = "adult" if age >= 18 else "minor"
print(status)
# Output: adult

This 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 3

Without :=, 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

ScenarioBest choice
One condition, single actionif
Two mutually exclusive pathsif-else
Three or more pathsif-elif-else
Secondary test inside a branchNested if
Simple value assignmentTernary x if c else y
Multi-value equality checks (Python 3.10+)match statement

Practice

Practice
What are the correct ways to write an if-else statement in Python?
What are the correct ways to write an if-else statement in Python?

Once you understand conditionals, the natural next step is repeating code with Python while loops and Python for loops.

Was this page helpful?