Contents
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.
Operator | Symbol | Example | Description |
---|---|---|---|
Logical AND | and | x and y | Returns the logical AND gate operation of x and y boolean values. |
Logical OR | or | x or y | Returns the logical OR gate operation of x and y boolean values. |
Logical NOT | not | not x | Returns 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
CopyOutput
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
CopyOutput
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.
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.