Booleans

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)
Python
Output

The result is False because and requires both conditions to be true.


What will be the output?

print(10 > 5 and 5 > 1)
Python

What will be the output?

print(10 / 2 == 5 and 15 > 10)
Python

What will be the output?

print(True and False)
Python

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)
Python
Output

What will be the output?

print(True or False)
Python

What will be the output?

print(10 > 5 or 5 > 1)
Python

What will be the output?

print(10 > 15 or False)
Python

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)
Python
Output

Here, isGreen is set to False, and we use not to reverse its value.


What will be the output?

print(not True)
Python

What will be the output?

print(not 2 > 1)
Python

You can even combine multiple Logical Operators. For example:

print(True and not False)
Python
Output

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))
Python
Output

What will be the output?

print((2 > 1 and 5 >= 6) or (False or True))
Python