Logical Operators
Combine conditions with and, or, not
Knowledge Debt detected
You can study this freely — but your score may plateau if these foundations have gaps. The Mastery badge requires them to be solid.
Explanation
Logical operators combine boolean values to create more complex conditions. They are the glue that turns simple true/false checks into powerful decision logic.
`and` — Both must be True
print(True and True)
print(True and False)
print(False and False)and returns True only if both operands are True. If either is False, the result is False.
age = 25
has_id = True
print(age >= 18 and has_id) # True — both conditions met`or` — At least one must be True
print(True or True)
print(True or False)
print(False or False)or returns True if at least one operand is True. Only returns False when both are False.
is_weekend = True
is_holiday = False
print(is_weekend or is_holiday) # True — at least one is True`not` — Invert a boolean
print(not True)
print(not False)not flips True to False and False to True.
is_logged_in = False
if not is_logged_in:
print("Please log in")Short-Circuit Evaluation
Python uses to skip unnecessary work:
def is_positive():
print("Checking...")
return True
print(False and is_positive()) # "Checking..." never prints
print(True or is_positive()) # "Checking..." never printsWith and, if the first value is False, Python already knows the result is False — no need to check the second. With or, if the first is True, the result is True regardless.
Truthiness and Logical Operators
Python's logical operators work with any values, not just booleans. They use / rules:
print(0 or "default") # "default" — 0 is falsy
print("hello" and 42) # 42 — "hello" is truthy, returns last value
print(not []) # True — empty list is falsyNote: and and or return the actual operand value (not just True/False) — this is why "hello" and 42 returns 42, not True.
Operator Precedence
not binds tightest, then and, then or:
print(not True or False) # not True is False; False or False = False
print(not (True or False)) # True or False is True; not True = False
print(True or True and False) # True and False = False; True or False = TrueUse parentheses when in doubt — they make your intent clear and override default precedence.
Examples
and, or, not basics
Combining comparisons with logical operators
x = 10
print(x > 5 and x < 20) # True
print(x < 5 or x > 8) # True
print(not x > 100) # TrueShort-circuit with or
Using or to provide a fallback value when the first operand is falsy
name = ""
display = name or "Anonymous"
print(display) # AnonymousShort-circuit with and
Guard against errors: check the list is non-empty before accessing items[0]
items = [1, 2, 3]
print(len(items) > 0 and items[0]) # 1
items = []
print(len(items) > 0 and items[0]) # FalseHow well did you understand this?
Next in Programming Fundamentals
Conditionals