Introduction to Python Logical Operators
Logical Operators are used to combine multiple conditions in a single statement. They are also known as boolean operators.
Operator | Example | Details |
---|---|---|
and | a > 5 and b < 20 | Returns True only if both statements are True, else False. |
or | a > 5 or b < 20 | Returns True if any statement is True, and returns False only if both statements are False. |
not | not(a > 5 and b < 20) | Returns True if expression inside parenthesis is False. |
Precedence and Associativity
Precedence of logical operators is as follows:
Logical Operator | Precedence |
---|---|
not | 1 |
and | 2 |
or | 3 |
Associativity of logical operators is as follows:
Logical Operator | Associativity |
---|---|
not, and, or | left 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.
age = 25
height = 1.6
print(age > 18 and height > 1.5)
False if any of the conditions is False.
age = 25
height = 1.4
print(age > 18 and height > 1.5)
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.
age = 25
height = 1.4
print(age > 18 or height > 1.5)
False if both the conditions are False.
age = 17
height = 1.4
print(age > 18 or height > 1.5)
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.
age = 60
print(age > 18 and age < 70)
age = 60
print(not(age > 18 and age < 70))