Python – Logical Operators
Logical Operators are used to combine simple conditions and form compound conditions.
Different Logical Operators in Python
The following table presents all the Logical operators in Python, with their symbol, description, and an example.
Operator Symbol | Description | Example |
---|---|---|
and | Returns True if both operands are True. | x and y |
or | Returns True if any of the operands is True. | x or y |
not | Returns the complement of given boolean operand. | not x |
1. Logical AND Operator
If x
and y
are two boolean values, then the expression of logical AND operation between these two values is
x and y
Example
In the following program, we take two variables with boolean values with different combinations, and print the result of their Logical AND operation.
main.py
x, y = True, True result = x and y #True print(f"{x} and {y} is {result}") x, y = True, False result = x and y #False print(f"{x} and {y} is {result}") x, y = False, True result = x and y #False print(f"{x} and {y} is {result}") x, y = False, False result = x and y #False print(f"{x} and {y} is {result}")
Output
True and True is True True and False is False False and True is False False and False is False
2. Logical OR Operator
If x
and y
are two boolean values, then the expression of logical OR operation between these two values is
x or y
Example
In the following program, we take two variables with boolean values with different combinations, and print the result of their Logical OR operation.
main.py
x, y = True, True result = x or y #True print(f"{x} or {y} is {result}") x, y = True, False result = x or y #False print(f"{x} or {y} is {result}") x, y = False, True result = x or y #False print(f"{x} or {y} is {result}") x, y = False, False result = x or y #False print(f"{x} or {y} is {result}")
Output
True or True is True True or False is True False or True is True False or False is False
3. Logical NOT Operator
If x
is a boolean value, then the expression of logical NOT operation with this value is
not x
Example
In the following program, we take a variable with boolean value, with different combinations, and print the result of its Logical NOT operation.
main.py
x = True result = not x print(f"not {x} is {result}") x = False result = not x print(f"not {x} is {result}")
Output
not True is False not False is True
Conclusion
In this Python Tutorial, we learned about Logical Operators in Python, and how to use them with boolean values, with the help of examples.