Logical Operators in Python
Logical Operators
58
Logical operators in Python are used to combine multiple conditions together to form a more complex condition that needs to be satisfied. There are three logical operators in Python, namely 'and', 'or' and 'not'.
- "and" logical operator:
The "and" operator returns True if both the conditions on either side of the operator are true, otherwise it returns False.
For example:
a = 10 b = 5 c = 20 if a > b and c > a: print("Both conditions are true")
In this case, the condition "a > b" and "c > a" are both true, so the output of the code will be "Both conditions are true".
- "or" logical operator:
The "or" operator returns True if either of the conditions on either side of the operator is true, otherwise it returns False.
For example:
a = 10 b = 5 c = 20 if a > b or c > a: print("At least one of the conditions are true")
In this case, at least one of the conditions - "a > b" and "c > a" is true, so the output of the code will be "At least one of the conditions are true".
- "not" logical operator:
The "not" operator returns True if the condition on the right side of the operator is False, and False if the condition on the right side is True.
For example:
a = 10 b = 5 if not a == b: print("a is not equal to b")
In this case, the condition "a == b" is False, so the output of the code will be "a is not equal to b".
March 25, 2023