Python If...Else Examples
Short, runnable programs that show python if, elif and else in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Python if, elif and else lesson.
1Checking for empty values with truthiness
An empty string counts as False and any non-zero number counts as True, so you can test values directly instead of writing != "" or > 0.
username = ""
unread = 3
if username:
print("Signed in as", username)
else:
print("Not signed in")
if unread:
print("You have", unread, "new messages")Expected outputNot signed in
You have 3 new messages
2Nested decisions at the airport
The bag check only matters once we know the passenger has a ticket, so it sits inside the first if, indented one more level.
has_ticket = True
bag_kg = 9
if has_ticket:
if bag_kg <= 7:
print("Go straight to the gate")
else:
print("Check in your bag: it is", bag_kg - 7, "kg over")
else:
print("Please buy a ticket first")Expected outputCheck in your bag: it is 2 kg over
3One-line choices with a conditional expression
value_if_true if condition else value_if_false picks one of two values. It is handy inside assignments and even inside print().
stock = 0
label = "In stock" if stock > 0 else "Sold out"
print(label)
n = 7
print(n, "is", "even" if n % 2 == 0 else "odd")Expected outputSold out
7 is odd
4Time ranges with chained comparisons
5 <= hour < 12 reads like maths: the hour is at least 5 and below 12. Chained comparisons keep range checks short and clear.
hour = 14
if 5 <= hour < 12:
print("Good morning")
elif 12 <= hour < 18:
print("Good afternoon")
else:
print("Good evening")Expected outputGood afternoon
Practise next
Python if, elif and else exercises → Back to the lesson
Python Logical Conditions examplesPython Nested If examplesPython Shorthand If (Ternary) examples