Computers constantly make decisions. They check if you are old enough for a site, or if your password matches. To do this, they use boolean values:
Booleans belong to the special type called
True and False. These represent yes/no answers.Booleans belong to the special type called
bool. They are not strings like "yes" or "no"; they are distinct data types that Python understands natively for logic.print(type(True))
print(type(False))You often create booleans by asking a question. This is where comparison operators come in. They compare two values and return
True or False. Since you already know how to assign variables, we can store these answers for later use.age = 20
is_adult = age >= 18
print(is_adult)
score = 95
passed = score > 60
print(passed)The Six Comparison Operators
x = 5
y = 10
print(x == y) # Equal?
print(x != y) # Not equal?
print(x < y) # Less than?
print(y > x) # Greater than?
print(x <= y) # Less than or equal to?
print(y >= x) # Greater than or equal to?Notice the last two operators:
<= and >=. These are useful when you need a boundary. For example, if an age must be 'at least' 18, that means it can be exactly 18 or higher. You would use age >= 18, not just age > 18. Missing the equals sign is a subtle bug.Combining Conditions
Real life involves multiple requirements. You might need to check if you have a ticket AND are an adult, or if it is raining OR snowing. Python lets you combine booleans using three logic words:
and, or, and not.has_ticket = True
is_adult = False
can_enter = has_ticket and is_adult
print(can_enter)
age = 70
free_entry = age < 10 or age > 65
print(free_entry)and is strict. It returns True only if BOTH sides are true. If one side fails, the whole thing becomes False. This is useful when every requirement must be met.or is flexible. It returns True if AT LEAST ONE side is true. Only if both fail does it return False. This works well for alternative options.is_raining = True
is_dry = not is_raining
print(is_dry)not flips the answer. If something was True, it becomes False. This is handy when you want to check for the opposite of a condition, like verifying that an error did NOT happen.