In this tutorial , we will learn how to perform logical operators in python. Logical operators are nothing but they are used to combine different conditions together . Logical operators perform logical comparision between multiple conditions or statements. Logical operators are also known as connectives because as it connects two values.
There are three different types of logical operators in python. They are : ‘and’ , ‘or’ , ‘not’.
- and operator : and operator returns True if both operands are True, else it returns False.
- Example : a< 10 and a < 15
- or operator : or operator returns True if one of the statement is True.
- Example : a < 7 or a < 5
- not operator : not operator returns False if the result is True.
- Example : not(a < 6 and a < 10)
Performance of Logical Operators
Example of ‘and’ operator :
a = 5 b = 10 if a > 1 and b < 11: print("both statements are True")
Output :
both statements are True
Explanation :
Here both statements are True ,so the code inside the if statement is executed.
Example of ‘or’ operator :
a = 5 b = 12 if a < 4 or y > 11: print("at least one statement is True") else: print("both statements are False")
Output :
First statement is False, but the second statement is True
Explanation :
As we are using or operator here the first statement returns False but the second statement returns True.
Example of ‘not’ operator :
a = 6 b = 10 if not a > b: print("a is not greater than b") else: print("a is greater than b")
Output :
not operator reverses the result of comparision 'a > b'
Explanation :
Here code inside the ‘if’ statement will only execute if a is not greater than b.