DEV Community

Cover image for PYTHON LOGICAL OPERATORS
Maame Afia Fordjour
Maame Afia Fordjour

Posted on

PYTHON LOGICAL OPERATORS

INTRODUCTION

Values and variables can be operated on using operators. These unique symbols are used to perform logical and arithmetic operations. The Operand is the value that the operator operates on.

To fully understand the notion, we will go over the definition of logical operators in Python in this post and also have a look at several applications that use logical operators in Python.

Python conditional statements (either True or False) use logical operators. They carry out operations involving logic in AND, OR, and NOT.

OPERATOR 'AND'

📌 Description: Returns True if both the operands are true.

📌 Example: a > 8 and a > 11

OPERATOR 'OR'

📌 Description: Returns True if either of the operands is true.

📌 Example: a < 8 or a > 11

OPERATOR 'NOT'

📌 Description: Returns True if the operand is false

📌 Example: not (a > 8 and a > 11)

Logical OR operator

If one of the operands is True, the logical OR operator returns True.

#Input:

a = 10
b = -10
c = 0
if a > 0 or b > 0: 
    print("Either of the number is greater than 0") 
else: 
    print("No number is greater than 0") 
if b > 0 or c > 0: 
    print("Either of the number is greater than 0") 
else: 
    print("No number is greater than 0")
Enter fullscreen mode Exit fullscreen mode
#Output:

Either of the number is greater than 0
No number is greater than 0
Enter fullscreen mode Exit fullscreen mode

Logical AND operator

If both operands are True, the logical AND operator returns True; otherwise, it returns False.

#Input:

a = 10
b = 10
c = -10
if a > 0 and b > 0: 
    print("The numbers are greater than 0") 
if a > 0 and b > 0 and c > 0: 
    print("The numbers are greater than 0") 
else: 
    print("Atleast one number is not greater than 0")
Enter fullscreen mode Exit fullscreen mode
#Output:

The numbers are greater than 0
Atleast one number is not greater than 0
Enter fullscreen mode Exit fullscreen mode

Logical NOT operator

One boolean value is used by the logical not operator. It returns False if the boolean value is True and vice versa.

#Input

a = 10

if not a: 
    print("Boolean value of a is True") 
if not (a%3 == 0 or a%5 == 0): 
    print("10 is not divisible by either 3 or 5") 
else: 
    print("10 is divisible by either 3 or 5")
Enter fullscreen mode Exit fullscreen mode
#Output:

10 is divisible by either 3 or 5
Enter fullscreen mode Exit fullscreen mode

Top comments (0)