Language: EN

python-operadores-logicos

Logical Operators in Python

Logical operators allow us to combine or modify boolean conditions to form more complex expressions.

List of logical operators

Operator and

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 True

Operator or

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 of the conditions is True

Operator not

The not operator is used to negate a condition, meaning it converts True to False and vice versa.

true = True
false = not true  # false is False

number = 5
is_greater_than_10 = number > 10
is_not_greater_than_10 = not is_greater_than_10

Usage examples:

Combination with and

age = 25
has_license = True

can_drive = (age >= 18) and has_license  # True

Combination with or

is_raining = False
is_cold = True

wants_to_stay_home = is_raining or is_cold  # True

Negation with not

is_day = True
is_night = not is_day  # False

Combination of Logical Operators:

It is possible to combine multiple logical operators in a single expression to create more complex conditions.

For example:

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 3 and 5 simultaneously
not_is_multiple_of_3 = not is_multiple_of_3  # False

Precedence 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:

  1. not
  2. and
  3. or

Therefore, in an expression with and, and is evaluated before or. However, it is not advisable to overuse this when writing our code. Feel free to use parentheses if it improves readability.