Python Logical Operators
Logical operators let you combine multiple conditions into a single, expressive boolean
expression. Python uses plain English — and,
or, not — instead of
symbols, making code read naturally. But there's far more to these operators than simple
True/False results: short-circuit evaluation makes code safer and faster, and
Python's unique ability to return the actual operand value — not just a boolean — unlocks
powerful one-line patterns used in professional code every day.
What Are Logical Operators?
Logical operators combine two or more boolean expressions into a single result.
Python uses three logical operators — and,
or, and not — written as
English keywords, unlike the &&,
||, ! symbols used in
Java, JavaScript, and C.
Python's logical operators do something most developers don't expect: they
return the actual operand value, not just
True or False. This
behaviour, combined with short-circuit evaluation, enables concise, idiomatic Python patterns
used in production code everywhere.
and and or do
not always return True or
False — they return one of their operands.
Only not always returns a bool. This makes
x or "default" a valid and idiomatic Python pattern.
The and Operator
The and operator returns the
first falsy operand it encounters — or the last operand if all
are truthy. It short-circuits: as soon as a falsy value is found, evaluation stops and that
value is returned immediately.
# Basic boolean and
print(True and True) # True
print(True and False) # False
print(False and True) # False
print(False and False) # False
# 'and' returns the actual operand — NOT just True/False
print(5 and 10) # 10 — both truthy, returns last
print(0 and 10) # 0 — 0 is falsy, short-circuits
print("" and "hi") # "" — empty str is falsy
print("hi" and "bye") # "bye" — both truthy, returns last
print(1 and 2 and 3) # 3 — all truthy, returns last
print(1 and 0 and 3) # 0 — 0 is first falsy
# Practical use: guard against None before attribute access
user = {"name": "Alice", "age": 25}
name = user and user.get("name")
print(name) # Alice
user2 = None
name2 = user2 and user2.get("name")
print(name2) # None — short-circuits, no AttributeError!
# Real-world: multiple conditions in if
age, has_ticket, is_member = 22, True, True
if age >= 18 and has_ticket and is_member:
print("Entry granted") # Entry granted
| A | B | A and B | Returned value |
|---|---|---|---|
True |
True |
True |
B (last operand) |
True |
False |
False |
B (first falsy) |
False |
True |
False |
A (short-circuits at A) |
False |
False |
False |
A (short-circuits at A) |
The or Operator
The or operator returns the
first truthy operand it encounters — or the last operand if
all are falsy. It short-circuits: as soon as a truthy value is found, evaluation stops and that
value is returned. This powers the popular default value pattern.
# Basic boolean or
print(True or True) # True
print(True or False) # True
print(False or True) # True
print(False or False) # False
# 'or' returns the actual operand
print(0 or "default") # "default" — 0 is falsy, returns right
print("" or "Guest") # "Guest" — empty str is falsy
print(None or 42) # 42 — None is falsy
print("hi" or "bye") # "hi" — "hi" is truthy, short-circuits
print(0 or 0 or 5) # 5 — all falsy until 5
print(0 or 0 or 0) # 0 — all falsy, returns last
# The default value pattern — very common in Python
username = ""
display = username or "Anonymous"
print(display) # Anonymous
config = None
port = config or 8080
print(port) # 8080
# First non-empty value from a list of candidates
env_val = ""
arg_val = ""
default = "localhost"
host = env_val or arg_val or default
print(host) # localhost
| A | B | A or B | Returned value |
|---|---|---|---|
True |
True |
True |
A (short-circuits at A) |
True |
False |
True |
A (short-circuits at A) |
False |
True |
True |
B (first truthy) |
False |
False |
False |
B (last operand) |
The not Operator
The not operator is the only logical operator that
always returns a pure boolean (True or
False). It inverts the truthiness of any value: truthy
becomes False, falsy becomes
True. It has the highest precedence among the three logical
operators.
# not always returns a bool
print(not True) # False
print(not False) # True
# not converts any value to bool then inverts
print(not 0) # True — 0 is falsy → not 0 = True
print(not 42) # False — 42 is truthy → not 42 = False
print(not "") # True — empty str is falsy
print(not "hello") # False — non-empty str is truthy
print(not []) # True — empty list is falsy
print(not [1, 2]) # False — non-empty list is truthy
print(not None) # True — None is falsy
# Equivalent to bool() then invert
print(not 5) # False — same as not bool(5)
print(type(not 5)) # <class 'bool'> — always bool
# Double negation — convert any value to explicit bool
print(not not 5) # True — same as bool(5)
print(not not 0) # False — same as bool(0)
print(not not "") # False
# Precedence — 'not' binds tighter than 'and' and 'or'
print(not True or True) # True — (not True) or True
print(not (True or True)) # False — not (True) = False
# Common pattern: check if something is empty / absent
items = []
if not items:
print("Cart is empty") # Cart is empty
True or
False. Equivalent to
not bool(x) — converts to bool then inverts.
not not 5 →
True. Equivalent to
bool(x).
if len(items) == 0 or
if items == [].
Truthiness — What Makes a Value Truthy or Falsy?
Every Python object can be used in a boolean context. Python calls the object's
__bool__() method (or
__len__() as fallback) to determine its truthiness. Knowing
which values are falsy by default is fundamental to idiomatic Python.
# ══ ALL FALSY VALUES IN PYTHON ══
print(bool(False)) # False — the boolean False
print(bool(None)) # False — None (absence of value)
print(bool(0)) # False — integer zero
print(bool(0.0)) # False — float zero
print(bool(0j)) # False — complex zero
print(bool("")) # False — empty string
print(bool([])) # False — empty list
print(bool(())) # False — empty tuple
print(bool({})) # False — empty dict
print(bool(set())) # False — empty set
print(bool(b"")) # False — empty bytes
# ══ COMMON TRUTHY SURPRISES ══
print(bool("False")) # True — non-empty string (even "False"!)
print(bool("0")) # True — non-empty string (even "0"!)
print(bool([0])) # True — list with one element (even 0)
print(bool(-1)) # True — any non-zero number
print(bool(0.001)) # True
# Custom class can define __bool__
class BankAccount:
def __init__(self, balance):
self.balance = balance
def __bool__(self):
return self.balance > 0
acc1 = BankAccount(100)
acc2 = BankAccount(0)
print(bool(acc1)) # True — has funds
print(bool(acc2)) # False — empty account
bool("False") is True!
The string "False" is non-empty, so it's truthy. Only the
empty string "" is falsy. Similarly,
bool([0]) is True — the
list has one element, even though that element is 0.
Short-Circuit Evaluation — In Depth
Short-circuit evaluation means Python stops evaluating an expression as soon as
the final result is determined, without evaluating the remaining operands. This is not just an
optimisation — it's a correctness guarantee that lets you write safe guards like
checking if a variable is not None before accessing its
attributes.
# Demonstrate short-circuit with side effects
def check_a():
print("check_a called")
return False
def check_b():
print("check_b called")
return True
# 'and' — check_a is False → check_b NEVER called
print(check_a() and check_b())
# check_a called
# False
# 'or' — check_b is True → second part NEVER called
print(check_b() or check_a())
# check_b called
# True
# Safety guard — prevents ZeroDivisionError
denominator = 0
if denominator != 0 and 100 / denominator > 10:
print("Large ratio")
# No error! — denominator != 0 is False, right side skipped
# Safety guard — prevents AttributeError on None
obj = None
if obj is not None and obj.is_active():
print("Active")
# No AttributeError! — obj is None short-circuits
# 'or' safety — use default if function returns None
def get_name():
return None # simulate DB miss
name = get_name() or "Unknown"
print(name) # Unknown
x is not None and x.method() — the left condition
protects the right from causing an AttributeError.
denominator != 0 and 100/denominator — the left
condition prevents ZeroDivisionError on the right.
Real-World Patterns with Logical Operators
The combination of short-circuit evaluation and operand return values makes logical operators a
tool for elegant, concise Python. Here are the most commonly used professional patterns — each
one replaces multiple lines of if/else with a single clean
expression.
# ── Pattern 1: Default value with 'or' ──────────────
def greet(name=None):
display = name or "Guest"
print(f"Hello, {display}!")
greet("Alice") # Hello, Alice!
greet() # Hello, Guest!
# ── Pattern 2: Conditional execution with 'and' ─────
debug = True
debug and print("Debug: system started") # runs only if debug=True
# ── Pattern 3: First truthy in a list ───────────────
env_port = None
arg_port = None
cfg_port = 5432
port = env_port or arg_port or cfg_port or 3306
print(port) # 5432
# ── Pattern 4: Validate multiple conditions ──────────
email = "alice@example.com"
password = "secure123"
agreed = True
if email and password and agreed:
print("Registration valid")
# ── Pattern 5: Inline ternary alternative ───────────
x = 10
label = x > 0 and "positive" or "non-positive"
print(label) # positive (use ternary for clarity)
# Better: label = "positive" if x > 0 else "non-positive"
# ── Pattern 6: Filter with 'not' ────────────────────
data = [1, None, 2, "", 3, 0, 4]
clean = [x for x in data if x] # keep truthy
print(clean) # [1, 2, 3, 4]
nulls = [x for x in data if not x] # keep falsy
print(nulls) # [None, '', 0]
# ── Pattern 7: all() and any() ──────────────────────
scores = [85, 92, 78, 90]
print(all(s >= 70 for s in scores)) # True — all passed
print(any(s >= 90 for s in scores)) # True — at least one ≥ 90
print(all(s >= 90 for s in scores)) # False — not all ≥ 90
all(iterable) returns
True if every element is truthy (equivalent to
and-ing all together).
any(iterable) returns
True if at least one element is truthy (equivalent to
or-ing all together). Both short-circuit on generator
expressions.
Practice Python Online — Free Compilers
Don't want to install anything yet? Practice all logical operator examples from this chapter directly in your browser with these free Python environments.
-
Python has three logical operators:
and,or,not— written as English keywords, not symbols. - and returns the first falsy operand, or the last operand if all are truthy. It short-circuits on the first falsy value.
- or returns the first truthy operand, or the last operand if all are falsy. It short-circuits on the first truthy value.
-
not always returns a pure
bool— it converts the value to bool then inverts it. Has highest precedence of the three. -
Falsy values:
False,None,0,0.0,0j,"",[],(),{},set(),b"". Everything else is truthy. -
Short-circuit evaluation makes guards safe:
x is not None and x.method()prevents AttributeError. -
Default value pattern:
val = user_input or "default"— if input is empty/None, use the default. -
Precedence:
not>and>or. Use parentheses for clarity in complex expressions. -
all()andany()extend logical operators across an entire iterable with short-circuit support.
The and operator does not always
return True or
False — it returns one of its
actual operands. The rule: it evaluates operands left-to-right
and returns the first falsy operand it encounters. If all
operands are truthy, it returns the last operand.
Short-circuit: as soon as a falsy value is found,
and stops evaluating — the right side is
never executed. This is the behaviour that makes guards like
x is not None and x.name safe: if
x is
None, the right side is never reached and no
AttributeError occurs.
print(5 and 10) # 10 — both truthy, returns last
print(0 and 10) # 0 — 0 is falsy, short-circuits
The or operator returns the
first truthy operand. If the left operand is falsy (empty
string, None,
0, [],
etc.), or evaluates and returns the right
operand. This creates a natural default value pattern:
name = user_input or "Guest"
port = config.get("port") or 8080
If user_input is empty or
None,
name becomes
"Guest". In Python 3.8+, the walrus-operator
:= and
x if x is not None else default are
alternatives when 0 or
False are valid inputs you don't want
replaced.
The complete set of falsy values in Python:
False,
None, 0,
0.0, 0j,
"" (empty string),
[] (empty list),
() (empty tuple),
{} (empty dict),
set() (empty set),
b"" (empty bytes). Custom objects with
__bool__ returning
False or
__len__ returning 0 are also falsy.
bool("False") is
True because Python only checks
length for strings. The string
"False" has 5 characters — it is non-empty,
so it's truthy. The content of the string is irrelevant. Only the empty
string "" is falsy.
Precedence from highest to lowest: not > and > or. This means
not binds most tightly,
and is evaluated next, and
or is evaluated last.
# not binds tighter than or:
print(not True or True) # (not True) or True = False or True = True
print(not (True or True)) # not (True) = False
# and binds tighter than or:
print(True or False and False)
# True or (False and False) = True or False = True
-
all(iterable)returnsTrueif every element is truthy (or the iterable is empty). It's equivalent toand-ing every element together. Short-circuits on the first falsy element. -
any(iterable)returnsTrueif at least one element is truthy. It's equivalent toor-ing every element. Short-circuits on the first truthy element. -
Both work perfectly with generator expressions for lazy evaluation:
all(x > 0 for x in nums)stops at the first non-positive number without processing the rest.
0 or "hello" or "world" return in Python?
True?
not True or False and True evaluate to in
Python?
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.