
Logical Operations
Logical operations are essential for decision-making, controlling program flow, error handling and more. They allow for the creation of program flow by assessing conditions and executing code accordingly, based on their truth values.
Python provides several logical operators that are used to perform logical operations on Boolean values or expressions.
Logical operators
and
or
not
Operator: and
The and
operator returns True if both operands are True, otherwise, it returns False.
Example 1
# Create two boolean variablesx = Truey = True
# Use 'and' operator result = x and y
print('Result of "x and y" is:')print(result)
Output:
Result of "x and y" is:
True
Example 2
# Create two boolean variablesx = Truey = False
# Use 'and' operator result = x and y
print('Result of x and y is:')print(result)
Output:
Result of x and y is:
False
Example 3
# Create two boolean variablesx = Falsey = False
# Use 'and' operator result = x and y
print('Result of x and y is:')print(result)
Output:
Result of x and y is:
False
Operator: or
The or
operator returns True if at least one of the operands is True, otherwise, it returns False.
Example 1
# Create two boolean variablesx = Truey = True
# Use 'or' operator result = x or y
print('Result of x or y is:')print(result)
Output:
Result of x or y is:
True
Example 2
# Create two boolean variablesx = Truey = False
# Use 'or' operator result = x or y
print('Result of x or y is:')print(result)
Output:
Result of x or y is:
True
Example 3
# Create two boolean variablesx = Falsey = False
# Use 'or' operator result = x or y
print('Result of x or y is:')print(result)
Output:
Result of x or y is:
False
operator: not
The not
operator negates the Boolean value of an expression. It returns True if the expression is False, and False if the expression is True.
Example 1
x = True
# Use "not" on xresult = not xprint(result)
Output:
False
Example 2
x = False
# Use "not" on xresult = not xprint(result)
Output:
True
Combining Logical Opeartors with Comparison Operators
The examples below illustrate how to integrate logical and comparison operators for advanced use cases.
Example 1
The expression (x > 5)
and (x < 20)
both evaluate to True, so the overall result is True.
x = 10result = (x > 5) and (x < 20)
print(result)
Output:
True
Example 2
The expression (x < 9)
evaluates to False, then the overall result is False with the and
operator.
x = 10result = (x > 5) and (x < 9)
print(result)
Output:
False
If we change the operator to or
instead, the overall result becomes to True.
Example 3
x = 10result = (x > 5) or (x < 9)
print(result)
Output:
True
Logical operations can alos be used with conditional statements (e.g. if... else...), which will be presented in the next section.