Python Logical Operators

Python Logical Operators

In this tutorial, you will learn about logical operators available in Python.

Logical operators are used to perform logical operations on Boolean values (True or False). They allow you to combine multiple conditions and determine the overall truth value of a complex expression.

There are three logical operators in Python. They are

  • Logical AND operator
  • Logical OR operator
  • Logical NOT operator

The following tables presents the Logical Operators, with respective operator symbol, description, and example.

OperatorSymbolExampleDescription
Logical ANDandx and yReturns the logical AND gate operation of x and y boolean values.
Logical ORorx or yReturns the logical OR gate operation of x and y boolean values.
Logical NOTnotnot xReturns the logical NOT gate operation of x boolean value.

Examples

1. Example using the “and” Operator

The and operator returns True if both the given conditions are True; otherwise, it returns False.

Python Program

x = 5
y = 10

result = (x > 0) and (y > 0)
print(result)  # Output: True

result = (x > 0) and (y < 0)
print(result)  # Output: False
Copy

Output

True
False

The and operator evaluates both conditions and returns the logical and of their results.

2. Example using the “or” Operator

The or operator returns True if at least one of the two given input conditions is True; otherwise, it returns False.

Python Program

x = 5
y = 10

result = (x > 0) or (y > 0)
print(result)  # Output: True

result = (x < 0) or (y < 0)
print(result)  # Output: False
Copy

Output

True
False

The or operator evaluates both conditions and returns the logical or of their results.

3. Example using the “not” Operator

The not operator returns the negation of the given condition. If the condition is True, not returns False; if the condition is False, not returns True.

Python Program

x = 5

result = not (x > 0)
print(result)  # Output: False
Copy

Output

False

Summary

In this tutorial of Python Operators, we learned about Logical Operators, and how to use them in programs for combining simple conditions to form compound conditions, and their working, with the help of example programs.

Code copied to clipboard successfully 👍