Logical operators in Python allow us to combine boolean conditions to form more complex expressions.
| Operator | Name | Description |
|---|---|---|
and | Logical AND | Returns True if both operands are True |
or | Logical OR | Returns True if at least one of the operands is True |
not | Logical NOT | Returns True if the operand is False |
If you want to learn more about Logical Operators
check the Introduction to Programming Course read more
List of logical operators
and Operator
The and operator is used to combine two conditions, and the resulting expression will be True only if both conditions are True.
a = 5
b = 10
c = 15
result = (a < b) and (b < c) # True, since both conditions are Trueor Operator
The or operator is used to combine two conditions, and the resulting expression will be True if at least one of the conditions is True.
a = 5
b = 10
c = 3
result = (a > b) or (b < c) # False, since neither condition is Truenot Operator
The not operator is used to negate a condition, meaning it converts True to False and vice versa.
true_value = True
false_value = not true_value # false_value is False
number = 5
is_greater_than_10 = number > 10
is_not_greater_than_10 = not is_greater_than_10Usage examples
Combination with and
age = 25
has_license = True
can_drive = (age >= 18) and has_license # TrueCombination with or
is_raining = False
is_cold = True
wants_to_stay_home = is_raining or is_cold # TrueNegation with not
is_day = True
is_night = not is_day # FalseCombination of logical operators
It is possible to combine multiple logical operators in a single expression to create more complex conditions.
number = 15
is_multiple_of_3 = (number % 3 == 0)
is_multiple_of_5 = (number % 5 == 0)
is_multiple_of_3_or_5 = is_multiple_of_3 or is_multiple_of_5 # True, since 15 is a multiple of 3
is_multiple_of_3_and_5 = is_multiple_of_3 and is_multiple_of_5 # False, since 15 is not a multiple of both 3 and 5 simultaneously
is_not_multiple_of_3 = not is_multiple_of_3 # FalsePrecedence of logical operators
When combining multiple logical operators in an expression, it is important to understand their precedence to correctly evaluate the expression.
The precedence of logical operators in Python follows this order:
notandor
Therefore, in an expression with and, and is evaluated before or. However, it is advisable not to overuse this when writing our code. Do not hesitate to use parentheses if it improves readability.