Introduction to Logical Operators
Discover how logical operators allow you to combine and evaluate boolean values, influencing the flow of your program based on the outcome of these logical conditions.
Sometimes, you need to make decisions in your program that depend on multiple conditions at the same time.
For example, when shopping for clothes, you might want to consider buying a shirt only if it has your favorite color and if it is within your budget.
In Python, we can use the Logical Operator and
to combine the 2 conditions:
is_favorite_color = True
is_within_budget = False
print(is_favorite_color and is_within_budget)
The result is False
because and
requires both conditions to be true.
What will be the output?
print(10 > 5 and 5 > 1)
What will be the output?
print(10 / 2 == 5 and 15 > 10)
What will be the output?
print(True and False)
Another Logical Operator in Python is or
. or
only requires one of the two conditions to be true.
Let's what happens if we replace and
with or
:
is_favorite_color = True
is_within_budget = False
print(is_favorite_color or is_within_budget)
What will be the output?
print(True or False)
What will be the output?
print(10 > 5 or 5 > 1)
What will be the output?
print(10 > 15 or False)
The final Logical Operator in Python is not
, which reverses the boolean value of an expression.
For example, let's assume we have a traffic light. If the traffic light is not green, we must stop:
isGreen = False
mustStop = not isGreen
print(mustStop)
Here, isGreen is set to False
, and we use not
to reverse its value.
What will be the output?
print(not True)
What will be the output?
print(not 2 > 1)
You can even combine multiple Logical Operators. For example:
print(True and not False)
Here, we get True
because not
reverts False
and both conditions are True
.
In Python, logical operators are evaluated from left to right. The order of evaluation is determined by operator precedence, with not
having the highest precedence, followed by and
, and then or
.
However, you can use parentheses to specify the order of evaluation explicitly, making the code easier to read. For example:
print((True or False) and (True and False))
What will be the output?
print((2 > 1 and 5 >= 6) or (False or True))