Python Logical operators are used to combine conditional statements. Python has three Logical operators the and
, or
, not
operators.
Operator | Meaning | Example |
---|---|---|
and | True if both the operands are true | x and y |
or | True if either of the operands is true | x or y |
not | True if operand is false (complements the operand) | not x |
Logical operators in Python
Simple example code performs Logical AND, Logical OR, and Logical NOT operations.
x = True
y = False
print('x and y is',x and y)
print('x or y is',x or y)
print('not x is',not x)
Output:
Check multiple conditions at the same time.
price = 9.99
print(price > 9 and price < 10)
print(price > 10 or price < 20)
print(not price > 10)
Precedence of Logical Operators
When you mix the logical operators in an expression, Python will evaluate them in the order which is called the operator precedence.
The following shows the precedence of the not
, and
, and or
operators:
Operator | Precedence |
---|---|
not | High |
and | Medium |
or | Low |
Python will evaluate them from the left to right:
a or b and c | means | a or (b and c) |
a and b or c and d | means | (a and b) or (c and d) |
a and b and c or d | means | ((a and b) and c) or d |
not a and b or c | means | ((not a) and b) or c |
Do comment if you have any doubts or suggestions on this Python operator topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.