Arithmetic operators · 6 / 18 Theory

Integers, floats and precision

Python has two types of numbers that you will use constantly: integers (int) and decimals (float). They behave almost the same, but there are differences worth knowing.

int: integers with no limit

Integers can be as large as you want, Python does not overflow:

print(2 ** 100)   # 1267650600228229401496703205376

float: approximate decimals

Decimals are stored in binary and many of them cannot be represented exactly. That is why surprising results sometimes appear:

print(0.1 + 0.2)          # 0.30000000000000004
print(0.1 + 0.2 == 0.3)   # False

It is not a Python bug: it happens in almost every language. That is why decimals should not be compared with ==. To compare, use math.isclose(a, b) or round first.

Mixing int and float

print(3 + 0.5)    # 3.5
print(10 / 4)     # 2.5
print(10 // 4)    # 2
print(float(3))   # 3.0

When they are mixed, the result is always a float.

Rounding a result

round(number, decimals) rounds the value:

print(round(19.999, 2))   # 20.0
print(round(3.14159, 2))  # 3.14

If you only want to display the number with a fixed number of decimals, use an f-string with :.2f. It is the most common option in the exercises:

price = 19.999
print(f"{price:.2f}")   # 20.00
print(f"{price:.3f}")   # 19.999

Careful with rounding .5

Python rounds .5 to the nearest even number, so round(2.5) is 2 and round(3.5) is 4. It is a statistical rule designed not to accumulate error.

A complete example

celsius = 25
fahrenheit = celsius * 9 / 5 + 32
print(fahrenheit)   # 77.0

Practice in the exercises about the arithmetic mean and converting degrees Celsius to Kelvin and Fahrenheit.