How to use booleans and comparisons
Create boolean results
The boolean values are exactly True and False. Comparisons produce booleans.
age = 20
print(age >= 18)
print(age == 20)
print(age != 21)
Combine conditions
and requires both conditions, or requires at least one, and not reverses truth.
has_ticket = True
age = 16
has_adult = True
can_enter = has_ticket and (age >= 18 or has_adult)
print(can_enter)
Understand truthiness
Empty strings and collections, zero, and None are false in conditions. Most other objects are true.
name = ""
items = [1, 2]
print(bool(name))
print(bool(items))
print(bool(0), bool(42))
Compare identity correctly
Use == to compare values. Use is for object identity, most commonly when testing against None.
answer = None
if answer is None:
print("No answer yet")
print([1, 2] == [1, 2])