What are logical operators in python :
The logical operation is mainly done with conditional statements. These are mainly used with two logical operands if the value of logical operands is either True or False. The result of the logical operator is used for the final decision making.
Three different types of logical operators are available in python:
1. OR or Logical OR
2. AND or Logical AND
3. NOT or Logical NOT
Logical OR :
The output of logical OR will be False only if both operands are False. If either of them has a True value, it will result True. The syntax ‘or’ is used for logical OR operation. Following are the input and result of different OR operations :
Logical AND :
The output of logical AND will be True only if both operands are True. If anyone of them is False, the result will be False. Syntax ‘and’ is used for logical AND operation. Input and results for different AND operations are as follow :
Logical NOT :
logical NOT is simple. It will just reverse the value. If the input is True, it will return False and if the input is False, it will return True.
Let’s try to learn how logical operator works with a simple python example (You can download it from here):
The commented numbers in the above program denote the step number below :
1. Ask the user to enter a number. Read it and store it in num variable.
2. In this, if condition, we are using logical AND operation using ‘and’ operator. It is checking if the number is greater than 9 and less than 100 or not. If yes, it will result True and the if condition will execute. Else, the else condition will execute.
3. This if condition is using logical OR operation using ‘or’ operator.The result of the expression inside the if statement will be True only if the number is divisible by 2 or 3. Then it will execute the print statement inside the if condition. Else, it will execute inside the else condition.
4. The last if condition is for logical NOT operation. It will execute if the number is not divisible by 5. Otherwise, else part will execute.
Sample Output :