Python Logical Operators
Logical operators in Python are AND, NOT and OR. In this article you'll see how to use them. While logical operators are not unique to Python, the coding style of Python is unique.
Related course: Complete Python Programming Course & Exercises
Logical AND operator in Python
The AND operator requires both inputs to be True for the output to be True. An input can be an expression like
x > 5 or
y > 20.
res = 10 > 5 and 10 > 20 print(res)
Logical OR operator in Python
The OR operator needs one of the expressions to be True, to output True.
res = 10 < 5 or 10 > 20 print(res)
In this case both are False,
10 <5 and
10 > 20 is False too. But if you change one of them to be True, the output is True.
Logical NOT operator in Python
A NOT operator inverts the input. So True becomes False and False becomes True.
# If it's established, it's not, if it's not print(not 10) print(not 0)
Contains two or more logical operators
Once there is more than one logical operator and / or, the core idea of its rules is short-circuit logic, so let's understand the short-circuit idea.
1 Expressions are run from left to right. If the left logical value of or is True, all expressions after shorting or (whether and or) will be output directly to the left side of or.
2 Expressions operate from left to right. If the left logical value of and is False, short all subsequent and expressions until or appears, output the left expression of and to the left of or, and participate in the next logical operation.
3 If the left side of the or is False, or the left side of the and is True, short circuit logic cannot be used.
# # Understand: and priority over or res = 5 and 0 or 20 and 30 # print(res)