Python Logical Operators

Python Logical Operators are used to combine two or more conditions and perform the logical operations using AND, OR, and NOT. Comparisons are used to compare two variables. What if we want to match more than one condition? Very simple, Python logical operators will do the trick for you. The below table outlines the and or not operator with examples.

OperatorsDescriptionExample
ANDIt will return true when both conditions are trueIf (age > 18 AND age <=35)
ORIt will return true when at least one of the conditions is trueIf (age > 35 OR age < 60)
NOTIf the condition is true, the logical NOT operator makes it falseIf age = True, then NOT( age) returns false.

The truth table behind the Logical AND and OR

Condition 1Condition 2Condition 1 AND Condition 2Condition 1 OR Condition 2
TrueTrueTrueTrue
TrueFalseFalseTrue
FalseTrueFalseTrue
FalseFalseFalseFalse

Python Logical Operators Example

This example will show you how to use Logical Operators in real-time. For this Python demo, we are using the IF Else statement.

>>> age = 29
# AND Example
>>> if age < 33 and age > 20:
	print ("Young Man")
else:
	print(" Not Eligible ")

# OR Example
>>> if age < 18 or age > 60:
	print(" Not Eligible to Work ")
else:
	print(" Please forward Your Resume ")
Python Logical Operators 1

In this Python Logical Operators example program, we created a new variable called age and assigned the value 29.

 age = 29

In the next line, we used the If Else Statement to check whether the age value is greater than 20 and Less than 33 using the Logical AND. If both the condition are True, then the first print statement will display. It means age must be greater than 20 and Less than 33.

print (" Young Man ")

If anyone of the statement is False, the following print statement will be displayed.

print(" Not Eligible ")

Next, we again used the If Else Statement. Still, this time, we used to check whether the age value is Less than 18 OR greater than 60 using the Logical OR. If anyone of the statement is TRUE, then the following print statement will print.

print(" Not Eligible to Work ")

If both the condition are False, the second print statement will be displayed.

print(" Please forward Your Resume ")

Please refer Comparison article.