Arithmetic and mathematics

Definition and syntax

The following symbols are used to do mathematics in Python. The symbols are known as operators because they perform operations on the numbers.

Symbol Meaning Example Result
+ Addition 5 + 5 10
- Subtraction 10 - 3 7
* Multiplication 20 * 3 60
/ Division 5 / 2 2.5
// Integer division (divides and rounds down) 15 % 6 2
% Modulus (gives the remainder after division) 15 % 6 3
** Exponent / Power of 5**2 25

Note

Notice in the examples how spaces can be used around mathematical operators to make code clearer.

Easy example

result = 15 + 5
Show/Hide Output
No output is given from this code

Python does the calculation 15 + 5 and stores the result 20 in the variable result.

Orders of precedence

Certain operations will be performed before others in Python. This is similar to how operations such as addition, multipication are carried out in mathematics. This is known as orders of precedence. You may know the term BIDMAS or BODMAS to remember the order.

The following table shows the orders of precedence. Operators at the top will be carried out before those underneath.

Operators Description
(, ) Brackets / Parentheses
** Exponentiation / Power
*, /, %, // Multiplication, division, modulus, floor division
+, - Addition, subtraction
<, <=, >, >=, !=, == Comparison operators
!=, == Equality operators
not, and, or Boolean operators

Examples

Example 1 - Subtraction

answer = 15 - 5
print(answer)
Show/Hide Output
10

Example 2 - Division

answer = 15 / 6
print(answer)
Show/Hide Output
2.5

Example 3 - Brackets

answer = 15 * (3 - 1)
answer2 = 15 * 3 - 1
print(answer)
print(answer2)
Show/Hide Output
30
44

Example 4 - Integer division

answer1 = 20 // 7
answer2 = 20 // 10
print(answer1)
print(answer2)
Show/Hide Output
2
2

For answer1 = 20 % 7, 7 goes into 20 twice. Therefore 2 is stored in answer1 then printed. This is integer division, so we do not store any fractions or decimal places. For answer2 = 20 % 10, 10 goes into 20 twice exactly. Therefore 2 is stored in answer2 then printed.

Example 5 - Modulus

answer1 = 20 % 7
answer2 = 20 % 10
print(answer1)
print(answer2)
Show/Hide Output
6
0

For answer1 = 20 % 7, 7 goes into 20 twice making 14. The remainder from 20 is 6 which is stored in answer1 then printed. For answer2 = 20 % 10, 10 goes into 20 twice exactly. The remainder is therefore 0 which is stored in answer2 then printed.

Example 6 - Exponent / Power

answer = 3**2
print(answer)
Show/Hide Output
9

3 to the power 2 = 9

Example 7 - Orders of precedence - without brackets

tempC = 37
tempF = tempC*9/5 + 32

print(tempF)
Show/Hide Output
98.6

Example 8 - Orders of precedence - with and without brackets

answerA = 103 - 3 * 5 + 5
answerB = (103 - 3) * (5 + 5)

print(answerA)
print(answerB)
Show/Hide Output
93
1000

Key points

Hint

The * symbol is produced by pressing SHIFT-8.