Logical Operators in Python

Combining Boolean expressions with and, or, and not

What Are Logical Operators?

Logical operators evaluate Boolean expressions and return True or False.

Operator Table

Operator Description Example
andTrue if both operands are TrueTrue and False → False
orTrue if at least one operand is TrueTrue or False → True
notInverts the Boolean valuenot True → False

Basic Examples

x = 5
y = 10

# and
print(x > 0 and y > 0)   # True (both conditions True)

# or
print(x < 0 or y > 0)    # True (second condition True)

# not
print(not (x == y))      # True (x == y is False, not False → True)

Short‑Circuit Evaluation

Python stops evaluating as soon as the result is determined:

def side_effect():
    print("Function called")
    return True

print(False and side_effect())  # side_effect() not called
print(True or side_effect())    # side_effect() not called

Truthy & Falsy Values

Any object can be tested for truthiness:

name = ""
print(not name)        # True (empty string is falsy)

items = [1, 2, 3]
if items and len(items) > 2:
    print("List has items")

Best Practices

Handy Functions

scores = [85, 90, 78]
print(all(score >= 70 for score in scores))  # True (all pass)
print(any(score < 60 for score in scores))   # False (none below 60)