Language: EN

python-operadores-logicos

Logical Operators in Python

Logical operators in Python allow us to combine boolean conditions to form more complex expressions.

OperatorNameDescription
andLogical ANDReturns True if both operands are True
orLogical ORReturns True if at least one of the operands is True
notLogical NOTReturns True if the operand is False

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 True

or 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 True

not 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_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.

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

  • not
  • and
  • or

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.