If Else Statement in Python (With Examples)

The if else statement in Python runs one block of code when a condition is true and another block when it’s false. You write the condition after if, end the line with a colon, and indent what should run:

if order_total >= 35:
    print("Free shipping")
else:
    print("Shipping: $5.99")

Online-store rules like shipping tiers and sales tax make good examples, so that’s what I used. Everything ran on Python 3.12.5 in the Windows Command Prompt.

You’ll see if/else, elif chains, nested ifs, the one-line form, combining conditions, and the two syntax errors beginners hit most.

Python if else syntax

Only one of the two blocks ever runs. The else part is optional; leave it out when there’s nothing to do on the false side:

order_total = 42.50

if order_total >= 35:
    print("Free shipping")
else:
    print("Shipping: $5.99")

order_total = 19.99
if order_total >= 35:
    print("Free shipping")
else:
    print("Shipping: $5.99")

Output:

Free shipping
Shipping: $5.99
Command Prompt output of a Python if else statement giving free shipping for a 42.50 order and charging 5.99 for a 19.99 order
The same if/else with two totals: one block runs each time, never both.

Indentation is the block. Python uses four spaces by convention, and every line in the block needs the same amount.

Using elif for more than two choices

elif (short for else if) adds more conditions. Python checks them from top to bottom and runs only the first one that’s true:

def shipping(total):
    if total >= 100:
        return "free 2-day"
    elif total >= 35:
        return "free ground"
    elif total > 0:
        return "$5.99 ground"
    else:
        return "empty cart"

for total in [150.00, 42.50, 12.00, 0]:
    print(f"${total:>7.2f} -> {shipping(total)}")

Output:

$ 150.00 -> free 2-day
$  42.50 -> free ground
$  12.00 -> $5.99 ground
$   0.00 -> empty cart
Command Prompt output of a Python if elif else chain mapping order totals to free 2-day, free ground, paid ground and empty cart
A $150 order matches the first test, so the later elif lines never run for it.

Order matters. If I’d put total >= 35 first, a $150 order would stop there and never get 2-day shipping. Put the strictest test at the top.

Nested if statements in Python

An if inside another if handles decisions that depend on an earlier one, like shipping rules that only apply to Alaska and Hawaii:

def can_ship(state, weight_lb):
    if state in ("AK", "HI"):
        if weight_lb > 50:
            return "freight only"
        else:
            return "air mail"
    else:
        return "ground"

print(can_ship("TX", 12))
print(can_ship("HI", 8))
print(can_ship("AK", 70))

Output:

ground
air mail
freight only

Nesting more than two levels gets hard to read. I usually flatten it with elif or by returning early from a function, as shipping() above does.

How do you write if else in one line in Python?

Use a conditional expression: value_if_true if condition else value_if_false. It picks a value, so it fits on the right side of an assignment:

total = 42.50

label = "free" if total >= 35 else "paid"         # conditional expression
print(label)

fee = 0 if total >= 35 else 5.99
print(f"fee: ${fee:.2f}")

if total > 0: print("cart has items")             # legal, but keep it for tiny cases

Output:

free
fee: $0.00
cart has items
Command Prompt output of Python one-line if else conditional expressions setting a label and a shipping fee
The conditional expression returns a value; a one-line if statement just runs a statement.

Keep one-liners for simple choices. Using if else in a list comprehension shows the same expression inside a comprehension.

Combining conditions with and, or and not

A single if can test several things at once. in checks membership, and empty values like "", 0 and [] count as false:

state, total, member = "CO", 60.00, True

if total >= 50 and member:
    print("member discount applies")

if state == "TX" or state == "CO":
    print("ships from Denver warehouse")

if state not in ("AK", "HI"):
    print("ground shipping available")

coupon = ""
if not coupon:                 # empty string counts as False
    print("no coupon entered")

Output:

member discount applies
ships from Denver warehouse
ground shipping available
no coupon entered

if not coupon is the usual way to check for an empty string. The if not condition in Python covers more truthiness cases.

Common if else errors: expected ‘:’ and IndentationError

Two mistakes cause most broken if statements: a missing colon and a block that isn’t indented. Here’s what Python reports for each:

code = 'total = 40\nif total >= 35\n    print("free")\n'
try:
    compile(code, "order.py", "exec")
except SyntaxError as err:
    print("SyntaxError:", err.msg, "| line", err.lineno)

code = 'total = 40\nif total >= 35:\nprint("free")\n'
try:
    compile(code, "order.py", "exec")
except SyntaxError as err:
    print(type(err).__name__ + ":", err.msg, "| line", err.lineno)

Output:

SyntaxError: expected ':' | line 2
IndentationError: expected an indented block after 'if' statement on line 2 | line 3
Command Prompt output of Python SyntaxError expected colon and IndentationError expected an indented block after if statement
The messages name the problem and the line, so read them before anything else.

elif and else also need to line up exactly with their if. An else indented one level too far gives you an invalid syntax error.

if, elif and else at a glance

KeywordWhen it runsRequired?
ifWhen its condition is trueYes, always first
elifWhen earlier tests failed and its own is trueNo, any number
elseWhen every test above was falseNo, at most one, always last

When you’re comparing one value against many fixed options, the match-case statement can read more cleanly than a long elif chain.

Ready to use conditions in real code? These guides build on them:

Frequently asked questions

What is an if else statement in Python?

It runs one block of code when a condition is true and a different block when it’s false. Both blocks are marked by indentation.

What is elif in Python?

Short for else if. It adds another condition after an if; Python runs the first branch whose condition is true and skips the rest.

Can I write if else on one line in Python?

Yes, with a conditional expression: fee = 0 if total >= 35 else 5.99.

Does Python have else if?

Not as two words. Use elif, which does the same job.

Why do I get ‘expected :’ in my if statement?

The line that starts with if, elif or else must end with a colon.

Can an if statement be empty?

No. Put pass in the block as a placeholder. The Python tutorial on if statements has the full rules.