Logical operators in python



Logical operators return either True or False depending on the value of the operands. They’re used when testing for a value. Moreover, it is also used in the decision-making process when the condition is more than one.

In this blog, you will learn about three types of logical operators with an example;

1. Logical AND operator

If both the operands are true then the condition becomes True.

Example:

>>> num1 = 23
>>> num2 = 31
>>> num1 > 20 and num2 < 33
True
>>> num1 > 24 and num2 >32
False

More example to demonstrate logical AND operator;

a = 10
b = 15
if a == 10 and b == 15:
    print("Condition is True")
    print(f"{a=} and {b=}")
else:
    print("a and b are not equal to 10 and 15.")

Output:

Condition is True
a=10 and b=15

Note: Else statement will be executed only if the condition fails.

2. Logical OR operator

Returns True if one of the statements is true. Returns False if both the statements or conditions are false.

Example:

>>> num1 = 23
>>> num2 = 31
>>> num1 > 20 or num2 == 40
True
>>> num1 > 30 or num2 < 30
False

More example to demonstrate logical OR operator;

day = str(input("Enter a day:")).title()
if day == "Saturday" or day == "Sunday":
    print("Happy weekend!")
else:
    print("You should be present at the school.")

Possible output:

# If the user enters Saturday
Enter a day: Saturday
Happy weekend!

# If the user enters Sunday
Enter a day: Sunday
Happy weekend!

# If the user enters Monday
Enter a day: Monday
You should be present at the school.


Recommended reading: The previous post was about Assignment operators



3. Logical NOT operator

Used to reverse the logical state of its operand. Returns False if the result is true.

Example:

>>> num1 = 23
>>> num2 = 31
>>> num1 > 20 and num2 > 30  
True
>>> not(num1 > 20 and num2 > 30)
False

More examples to demonstrate on logical NOT operator;

# program to check on eligibility to vote
# logical NOT operator
age = int(input("Enter age:"))
if not age < 18:
    print("Eligible to vote!")
else:
    print("Not eligible to vote!")

Possible output:

# If the age is below 18
Enter age:17
Not eligible to vote!

# If the age is above 18
Enter age:30
Eligible to vote!

last note: Bhutan python coder is always open to all the enthusiast programmers to improve the article here. Improve us through the comment section below. Moreover, we also accept a guest post, so that you can submit us your original content with your detail. We will review and post on your behalf. Send us your content here.

Other operators used are:



Python official documentation