Skip to content

Numbers

Numbers are one of the most useful data types in all of programming.

The two most commonly used number types are integers (int) and decimals (float).

Doing arithmetic:

>>> 7 + 2
9
>>> 7 - 2
5
>>> 7 * 2
14
>>> 7 / 2
3.5
>>> 7 // 2
3
>>> 7 % 2
1
>>> 7 ** 2
49

Division always produces a float

This is the case even in exact division:

>>> 10 / 2
5.0

n // m and n % m are complements of each other, and both produce integer results. The first produces the completed, whole part of the division. The other produces the remainder, or what's left over after the division.

0.1 + 0.2 is not equal to 0.3

Floating-point numbers cannot be represented exactly in Python.

Python always prints an approximation of the value stored by the machine. so, never compare two decimal values without rounding to the same decimal places first.

To learn more about this, read the Floating-point arithmetic module in the Official Python tutorial.

Precedence — the order of operations

Python follows normal math order: ** first, then * / // %, then + -. Use parentheses whenever you're unsure or want to be clear:

>>> 2 + 3 * 4
14
>>> (2 + 3) * 4
20
>>> 2 ** 3 ** 2
512

Grouping is right-to-left

The last expression in the previous example may be surprising. ** groups right-to-left, meaning 3**2 is evaluated first.

When in doubt, parenthesize.