Python Logical Conditions Examples
Short, runnable programs that show python logical conditions in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Python Logical Conditions lesson.
1Build a rule from named pieces
Giving each part of the rule its own name keeps the final condition short, and lets you print any part to see why a decision came out the way it did.
age = 13
has_ticket = True
with_adult = True
film_rating = 15
old_enough = age >= film_rating
has_permission = old_enough or with_adult
can_watch = has_ticket and has_permission
print("Old enough:", old_enough)
print("Has permission:", has_permission)
print("Can watch:", can_watch)Expected outputOld enough: False
Has permission: True
Can watch: True
2Short-circuiting as a safety guard
Indexing an empty string with [0] would raise an IndexError. Checking the length first with and means the risky half is only evaluated when it is safe.
username = ""
if len(username) > 0 and username[0] == "A":
print("Starts with A")
else:
print("Empty, or does not start with A")
username = "Asha"
if len(username) > 0 and username[0] == "A":
print("Starts with A")
else:
print("Empty, or does not start with A")Expected outputEmpty, or does not start with A
Starts with A
3Flipping a whole condition with not
not (A or B) is the same as not A and not B. When you negate a combined condition, you flip each comparison and swap or for and (and the other way round). Two equivalent ways to write it:
temperature = 31
humidity = 80
too_uncomfortable = temperature > 30 or humidity > 70
comfortable = not (temperature > 30 or humidity > 70)
comfortable_other_way = temperature <= 30 and humidity <= 70
print(too_uncomfortable)
print(comfortable)
print(comfortable_other_way)Expected outputTrue
False
False
4in and not in with lists, tuples and text
The same operator works on lists, tuples and strings. With text, in checks for a smaller piece of text anywhere inside it.
roles = ["editor", "viewer"]
weekend = ("Sat", "Sun")
message = "Your order has shipped"
print("admin" in roles)
print("Mon" in weekend)
print("shipped" in message)
print("refund" not in message)
print("ship" in message and "refund" not in message)Expected outputFalse
False
True
True
True
5or as a fallback value
or returns the first operand that counts as True, or the last operand if none do. That makes entered or default a compact way to say "use this unless it is empty".
default_city = "Pune"
entered_city = ""
city = entered_city or default_city
print(city)
entered_city = "Oslo"
city = entered_city or default_city
print(city)
print(0 or 5, 3 or 5)Expected outputPune
Oslo
5 3
Practise next
Python Logical Conditions exercises → Back to the lesson
Python Operators examplesPython Shorthand If (Ternary) examplesPython Truthy and Falsy Values examples