The three logical operators in Python are and
, or
, and not
. These operators can be used in conditions, such as in an if
statement, or in combination with comparison operators to create more complex conditions.
Python supports the following logical operators:
and
: ReturnsTrue
if both the operands are true, otherwise, it returns False.or
: ReturnsTrue
if either of the operands is true, otherwise, it returns False.not
: Reverse the logical state of the operand. If a condition is true, thennot
operator will make it false.
Example
Python
# and operator
a = True
b = False
print(a and b) # False
# or operator
a = True
b = False
print(a or b) # True
# not operator
a = True
print(not a) # False
You can also use logical operators with comparison operators. For example:
Python
a = 5
b = 10
# using `and` operator
if a < 8 and b > 8:
print("Both conditions are true")
else:
print("One or both conditions are false")
# using `or` operator
if a < 2 or b > 8:
print("One or both conditions are true")
else:
print("Both conditions are false")
Note that and
and or
have a short-circuit evaluation, meaning that if the first operand already determines the outcome of the operation, the second operand will not be evaluated.
In python True
is equivalent to 1
and False
is equivalent to 0
. So you can also use logical operators with numbers.
Python
a = 1
b = 0
print(a and b) # 0
print(a or b) # 1
I hope you find this tutorial helpful in understanding logical operators in Python.