Lesson 5 / 1145%

Lesson 5

Operators

18 min

Arithmetic, comparison and logical operators to calculate and compare.

Definition

An operator is a symbol or a keyword that performs an operation on one or more values, called operands. In3 + 4, the+symbol is the operator, and3and4are the operands. Python offers arithmetic,assignment, comparison andlogical operators.

Arithmetic operators

Python can do all the usual mathematical operations. Here are the operators to know:

  • +addition,-subtraction,*multiplication.
  • /division (the result is always a float).
  • //integer division (only the whole part is kept).
  • %modulo: the remainder of the division.
  • **power.
arithmetic.py
print(10 + 3)    # 13
print(10 - 3)    # 7
print(10 * 3)    # 30
print(10 / 3)    # 3.3333333333333335
print(10 // 3)   # 3
print(10 % 3)    # 1
print(2 ** 8)    # 256

The modulo is very useful: for examplen % 2 == 0tells you whether a number is even, andn % 5 == 0whether a number is a multiple of 5. It’s also used for anything that cycles around, like the hours on a clock or the days of the week.

Operator precedence

As in mathematics, Python follows an order of precedence: first powers, then multiplication and division (including//and%), and finally addition and subtraction. Parentheses let you force the order you want, and improve readability: don’t hesitate to use them.

precedence.py
print(2 + 3 * 4)     # 14  (multiplication comes first)
print((2 + 3) * 4)   # 20  (parentheses change the order)
print(2 ** 3 * 2)    # 16  (8 * 2)
print(10 - 4 - 3)    # 3   (calculated from left to right)

Assignment operators

To modify a variable based on its current value, you use shortcuts. Each arithmetic operator has its assignment version:+=,-=,*=,/=,//=,%= and**=.

assignment.py
score = 10
score += 5     # equivalent to score = score + 5  -> 15
score -= 3     # -> 12
score *= 2     # -> 24
score //= 5    # -> 4
print(score)
Screenshot: a terminal showing the result of running the assignment.py script, with the value 4 displayed.

Comparison operators

They compare two values and return a boolean (TrueorFalse). This result will very soon be used to make decisions in a program, with conditions.

comparison.py
age = 18

print(age == 18)   # True  (equal to)
print(age != 18)   # False (not equal to)
print(age > 20)    # False (greater than)
print(age >= 18)   # True  (greater than or equal to)
print(age < 30)    # True  (less than)
print(age <= 17)   # False (less than or equal to)

You can also compare text:"python" == "python"isTrue, but the comparison is case-sensitive, so"Python" == "python"isFalse. Finally, Python lets you chain comparisons, as in mathematics:

chaining.py
grade = 14

print(0 <= grade <= 20)       # True: the grade is between 0 and 20
print("Python" == "python")   # False: case matters

Warning

Don’t confuse=(assigning a value to a variable) with==(testing equality). It’s one of the most common mistakes among beginners.

Logical operators

They combine several conditions:and(both must be true),or(at least one must be true) andnot(inverts the result).

logic.py
age = 20
has_license = True

print(age >= 18 and has_license)   # True
print(age < 18 or has_license)     # True
print(not has_license)             # False
Screenshot: a terminal showing the result of running the logic.py script, with the three results displayed one below the other.

When you mix several logical operators,notis evaluated first, thenand, thenor. When in doubt, add parentheses: the code will be easier to reread.

advanced_logic.py
age = 16
accompanied = True

# Can enter if they are an adult, or if they are a minor but accompanied
can_enter = age >= 18 or (age >= 12 and accompanied)
print(can_enter)   # True

Common errors

  • Confusing = and ==: the first assigns a value, the second tests equality.
  • Forgetting that / returns a float:10 / 2gives5.0, not5. Use//to get an integer.
  • Comparing a text and a number:"5" == 5isFalsebecause the types are different.

Exercise

Write a program that asks the user for two numbers, then displays their sum, their product, the result of the integer division and the remainder of the division. Remember to convert the inputs withint().

Going further

Ask for an integer and displayTrueif it is even and greater than 10,Falseotherwise, in a single expression.