Skip to content
Laviyx Learn

Try

Python course menu

Python if else: Choose Between Two Paths

Learn Python if-else with clear examples: run one block when a condition is true and another when it is false, even/odd checks, the one-line conditional expression (ternary), and common mistakes.

Beginner5 min readUpdated
On this page

An if statement runs code when a condition is true. Often you also want something to happen when it is false. else gives your program exactly two paths: one or the other always runs, never both.

Syntax#

Python
if condition:
    # runs when condition is True
else:
    # runs when condition is False

else has no condition of its own; it catches every case the if did not. It also ends with a colon, and its body is indented.

Example#

Python
age = 16

if age >= 18:
    print("You can vote")
else:
    print("You cannot vote yet")
Output
You cannot vote yet

Even or odd#

The remainder operator % makes this classic check easy:

Python
number = 7

if number % 2 == 0:
    print(f"{number} is even")
else:
    print(f"{number} is odd")
Output
7 is odd

Setting a value in each branch#

A very common pattern is choosing a value:

Python
amount = 1200

if amount >= 1000:
    shipping = 0
else:
    shipping = 50

print(f"Shipping: {shipping}, Total: {amount + shipping}")
Output
Shipping: 0, Total: 1200

Because one branch always runs, shipping is guaranteed to exist after the if/else.

One-line if-else (conditional expression)#

When each branch just produces a value, Python has a compact form:

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

Read it as: value_if_true if condition else value_if_false. It is handy inside other expressions too:

Python
items = 3
print(f"{items} item" + ("" if items == 1 else "s"))
Output
3 items

Comparisons are exact#

String comparisons are case-sensitive, which matters for passwords and answers:

Python
password = "secret123"
attempt = "Secret123"

if attempt == password:
    print("Welcome!")
else:
    print("Wrong password")
Output
Wrong password

For answers where case should not matter, compare lowercase versions: attempt.lower() == expected.lower().

Common mistakes#

Practice#

Practice exercise

A shop gives a 10% discount on bills of 2000 or more. Write a program with bill = 2500 that prints the amount to pay. Then write the same logic using a one-line conditional expression.

Show hint

if bill >= 2000: then pay = bill * 0.9, else: pay = bill.

Show solution
Python
bill = 2500

if bill >= 2000:
    pay = bill * 0.9
else:
    pay = bill

print(f"To pay: {pay}")

# One-line version
pay = bill * 0.9 if bill >= 2000 else bill
print(f"To pay: {pay}")
Output
To pay: 2250.0
To pay: 2250.0

Key takeaway#

Finished this lesson?