Logical Operators in Python

In this tutorial, you will learn about logical operators. In python logical operators are used to combine conditional expressions. These operators are used to evaluate whether a certain condition us true or not. There are three types of logical operators in Python: and, or, and not.

In Python Logical operators are used to combine multiple conditions together and evaluate them as a single boolean expression.

Now lets discuss each Logical operator in detail:

Logical AND (and):

The logical AND operator returns True if both conditions are True, otherwise, it returns False.
For example: The code checks if x is greater than y and z. if two conditions are true it will print “x is largest number” otherwise it will print the statement in else condition.

x = 10
y = 20
z = 30
if x > y and y > z:
     print("x is largest number.")
else:
     print("x is not the largest number.")

Output:

x is not the largest number.

Logical OR (or);

The logical OR operator returns True if at least one of the condition is True, otherwise, it returns False.
For example: The code checks if x is greater than y and z. if at least greater than one value then it will print corresponding message, otherwise it will print x is smallest number.

x = 30
y = 50
z = 10
if x > y or x > z:
     print("x is at least larger than one number.")
else:
     print("x is smallest number")

Output:

x is at least larger than one number.

Logical NOT (not):

The Logical NOT operator returns True if the conditional expression returns False and vice-versa. This operator works with a single boolean value. if the boolean value is True it will returns False and vice-versa.
For example: The code checks if x is equal to 5 or not.

x = 10
if not x == 5:
    print("x is not equal to 5")

Output:

x is not equal to 5

Advantages of Logical operators:

  • Combining conditions
  • Improving code readability
  • Reducing code duplication
  • Making code more efficient

Conclusion:

In conclusion, logical operators in python are essential for creating complex conditions and controlling the flow of programs. Logical operators are used to perform variety of tasks in python. It can help you to write more efficient, readable and maintainable code.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top