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!")The not operator is a unary operator, meaning it works on a single condition. It simply inverts the boolean value of the condition. If the condition is True, not makes it False, and vice-versa.
is_raining = False
if not is_raining:
print("No need for an umbrella.")You can also combine multiple logical operators, just like in mathematics. However, be mindful of the order of operations. In Python, not is evaluated first, then and, and finally or. You can use parentheses to explicitly control the order of evaluation and make your logic clearer.
has_ticket = True
wallet_has_cash = False
is_member = True
# Example with parentheses for clarity
if (has_ticket and wallet_has_cash) or is_member:
print("You can enter the event.")graph TD
A[Start]
B{Is condition 1 True?}
C{Is condition 2 True?}
D[Result is True]
E[Result is False]
A --> B
B -- Yes --> C
B -- No --> E
C -- Yes --> D
C -- No --> E
Understanding how to use comparison and logical operators is fundamental to writing any non-trivial program. They are the tools that allow your code to react to different situations and make informed decisions, paving the way for more complex control flow structures like if statements, while loops, and for loops.