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.
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#
if condition:
# runs when condition is True
else:
# runs when condition is Falseelse 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#
age = 16
if age >= 18:
print("You can vote")
else:
print("You cannot vote yet")You cannot vote yetEven or odd#
The remainder operator % makes this classic check easy:
number = 7
if number % 2 == 0:
print(f"{number} is even")
else:
print(f"{number} is odd")7 is oddSetting a value in each branch#
A very common pattern is choosing a value:
amount = 1200
if amount >= 1000:
shipping = 0
else:
shipping = 50
print(f"Shipping: {shipping}, Total: {amount + shipping}")Shipping: 0, Total: 1200Because 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:
age = 20
status = "adult" if age >= 18 else "minor"
print(status)adultRead it as: value_if_true if condition else value_if_false. It is handy inside other expressions too:
items = 3
print(f"{items} item" + ("" if items == 1 else "s"))3 itemsComparisons are exact#
String comparisons are case-sensitive, which matters for passwords and answers:
password = "secret123"
attempt = "Secret123"
if attempt == password:
print("Welcome!")
else:
print("Wrong password")Wrong passwordFor 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
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}")To pay: 2250.0
To pay: 2250.0Key takeaway#
Finished this lesson?