Python can be used as a very powerful calculator. Arithmetic operators are the symbols that tell it which operation to perform on two values, called operands. You will use them in every exercise of this lesson.
The seven operators
| Operator | Name | Example | Result |
|---|---|---|---|
+ | Addition | 7 + 2 | 9 |
- | Subtraction | 7 - 2 | 5 |
* | Multiplication | 7 * 2 | 14 |
/ | Division | 7 / 2 | 3.5 |
// | Floor division | 7 // 2 | 3 |
% | Modulo (remainder) | 7 % 2 | 1 |
** | Power | 7 ** 2 | 49 |
Try them
print(7 + 2) # 9
print(7 - 2) # 5
print(7 * 2) # 14
print(7 / 2) # 3.5
print(7 // 2) # 3
print(7 % 2) # 1
print(7 ** 2) # 49
With variables
Operands can be numbers written directly or variables. You can show the result right away or store it in another variable to use it later.
x = 5
square = x ** 2
print(x + square) # 30
Which type of number does it return?
+,-,*,//,%and**with two integers give an integer./always gives a decimal number (float), even when the result is exact:6 / 3is2.0.- If any operand is a decimal, the result is a decimal too:
2 * 1.5is3.0.
Common mistake: using ^ for powers
In other languages and on calculators ^ means power, but in Python it is a different operation (bitwise XOR). To raise a number to a power always use **:
print(2 ** 3) # 8 -> power
print(2 ^ 3) # 1 -> not a power
Practice these operators in the exercises about squares, multiplying three factors and the basic calculator.