
Comparison and Logical Operators
Now that we understand how to compare values, let's dive into how Python uses these comparisons to control the flow of your programs. This is where we start making your code intelligent, allowing it to make decisions and repeat actions based on specific conditions.
Comparison operators are the building blocks for making decisions. They evaluate to either True or False, which are Python's boolean data types. You've already encountered some of these: == (equal to), != (not equal to), < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to).
age = 18
print(age >= 18) # Output: True
print(age < 18) # Output: FalseBeyond simple comparisons, we often need to combine multiple conditions. This is where logical operators come in handy. Python provides three primary logical operators: and, or, and not.
The and operator returns True if both conditions it connects are True. Think of it as requiring both parts of a statement to be true for the whole statement to be true.
temperature = 25
is_sunny = True
if temperature > 20 and is_sunny:
print("It's a perfect day for a picnic!")The or operator returns True if at least one of the conditions it connects is True. This is useful when you want to allow for multiple possibilities.
day_of_week = "Saturday"
if day_of_week == "Saturday" or day_of_week == "Sunday":
print("It's the weekend!")