Skip to main content

Logical Operators

Logical operators are those that make comparisons between values and seek an answer whether it's True or False.

With them, our program can take different paths.

  • == Will compare if one is equal to the other. It's different from = which assigns the value into a variable.
  • != Will compare if they're different.
  • > Greater than
  • >= Greater than or equal to
  • < Less than
  • <= Less than or equal to
  • in Is inside. We use more for strings and lists
  • is Used to check if it is or isn't. Used in strings.
>>> num1 = 5
>>> num2 = 3
>>> num1 == num2
False
>>> num1 >= num2
True
>>> num1 < num2
False
>>> num2 == num2
True
>>> name1 = "David"
>>> name2 = "Pedro"
>>> name1 == name2
False
# I want to know if the length of the names is equal
>>> len(name1) == len(name2)
True

We also have and (&), or (|) and xor (^) which compare bool values.

The "and" operator is a binary operator that returns true (or "true") if all the conditions surrounding it are true. Otherwise, it returns false (or "false"). Here's a truth table showing all possible results:

Condition ACondition BResult
FalseFalseFalse
FalseTrueFalse
TrueFalseFalse
TrueTrueTrue

Therefore, the expression with the "and" operator will only be true if both conditions involved are true.

a = True
b = False

result = a & b
print(result) # Output: False

On the other hand, the "or" operator is also a binary operator, but returns true if at least one of the conditions involved is true. It returns false only if both conditions are false. Here's the corresponding truth table:

Condition ACondition BResult
FalseFalseFalse
FalseTrueTrue
TrueFalseTrue
TrueTrueTrue

Thus, the expression with the "or" operator will be true if at least one of the conditions involved is true.

a = True
b = False

result = a | b
print(result) # Output: True