The Python Comparison Operators are used to compare two variables, what if we want to compare more than one condition? Very simple, python logical operators will do the trick for you.
Python Logical Operators are used to combine two or more conditions and perform the logical operations using Logical AND, Logical OR and Logical NOT. Below table describes them
|Python Logical Operators||DESCRIPTION||EXAMPLE|
|AND or Logical AND||It will return true when both conditions are true||If (age > 18 AND age <=35)|
|OR or Logical OR||It will returns true when at-least one of the condition is true||If (age > 35 OR age < 60)|
|NOT or Logical NOT||If the condition is true, logical NOT operator makes it false||If age = True then NOT( age) returns false.|
Let us see the truth tables behind the Python Logical Operators. Please refer them for better understanding
Following table is the truth table behind the Logical AND Operator
|Condition 1||Condition 2||Condition 1 AND Condition 2|
Following table is the truth table behind the Logical OR Operator
|Condition 1||Condition 2||Condition 1 OR Condition 2|
Python Logical Operators Example
This example will show you, How to use Python Logical Operators in real-time
>>> age = 29 # Logical AND Example >>> if age < 33 and age > 20: print ("Young Man") else: print(" Not Eligible ") # Logical OR Example >>> if age < 18 or age > 60: print(" Not Eligible to Work ") else: print(" Please forward Your Resume ")
First we created new variable called age and assigned value 29
age = 29
In the next line we used If Else Statement to check whether the age value is greater than 20 and Less than 33 (Logical AND). If both the condition are True then first print statement will be displayed. It means age must be greater than 20 and Less than 33.
print (" Young Man ")
If any one of the statement is False, following print statement will be displayed
print(" Not Eligible ")
In the next line we again used If Else Statement but this time we used to check whether the age value is Less than 18 OR greater than 60 (Logical OR). If any one of the statement is TRUE then following print statement will be displayed
print(" Not Eligible to Work ")
If both the condition are False, second print statement will be displayed.
print(" Please forward Your Resume ")