Python Logical Operators


Introduction to Python Logical Operators

Logical Operators are used to combine multiple conditions in a single statement. They are also known as boolean operators.

OperatorExampleDetails
anda > 5 and b < 20Returns True only if both statements are True, else False.
ora > 5 or b < 20Returns True if any statement is True, and returns False only if both statements are False.
notnot(a > 5 and b < 20)Returns True if expression inside parenthesis is False.

Precedence and Associativity

Precedence of logical operators is as follows:

Logical OperatorPrecedence
not1
and2
or3

Associativity of logical operators is as follows:

Logical OperatorAssociativity
not, and, orleft to right

Logical Operators

Logical AND Operator

The Logical AND Operator returns true if all the statements are true, and if any of them is false, then it returns False. We can have more than two conditions as well.

True if both the conditions are True.

In [1]:
age = 25
height = 1.6

print(age > 18 and height > 1.5)
True

False if any of the conditions is False.

In [2]:
age = 25
height = 1.4

print(age > 18 and height > 1.5)
False

Logical OR Operator

The Logical OR Operator returns true if any of the statements are true, and if all of them are false, then it returns False. Here also, we can have more than two conditions.

True if any of the conditions is True.

In [1]:
age = 25
height = 1.4

print(age > 18 or height > 1.5)
True

False if both the conditions are False.

In [2]:
age = 17
height = 1.4

print(age > 18 or height > 1.5)
False

Logical NOT Operator

The Logical NOT Operator is used to reverse the result of the expression inside the parenthesis. If the expression inside the parenthesis results in True, then the Logical NOT Operator returns False and if the expression inside the parenthesis results in False, then the Logical NOT Operator returns True.

Reverses the result of expression inside parenthesis.

In [1]:
age = 60

print(age > 18 and age < 70)
True
In [2]:
age = 60

print(not(age > 18 and age < 70))
False

References

  1. Logical operators
  2. Python Logical Operators: What is ‘&&’?
  3. Python Logical Operators