all Python 3Conditionalsconstruct
and, or, not
logic
The logical operators. and — both are true; or — at least one is true; not — negation. They short-circuit (lazy evaluation).
Syntax
a and b | a or b | not a
The non-obvious part: and and or return one of the operands, not True/False — "a or b" yields a when a is truthy, otherwise b, which is why "name or 'guest'" is the classic default-value idiom. Only not is guaranteed to give a clean bool.
Examples
print(True and False) # → False
print(True or False) # → True
print(not True) # → False
age, has_id = 20, True
print(age >= 18 and has_id) # → True
x = 5
print(x < 0 or x > 3) # → True
print(1 < x < 10) # → True (цепочка = неявный and)
name = "" or "Гость"
print(name) # → Гость (короткое замыкание or)
val = None
safe = val and val.strip() # → None (не вызывает ошибку из-за and)
See also
Open in the full glossarydocs.python.orgReport an inaccuracy