CodeMIRAI
0 XP

Numbers

2 min read 7 runnable examples Quiz included

Python has two main number types: integers (int) for whole numbers and floats (float) for numbers with a decimal point.

Integers

Integers can be as large as you like; Python never overflows.

Python
population = 8_100_000_000      # underscores make big numbers readable
print(population)
print(2 ** 100)                  # 2 to the power 100

Floats

Python
pi = 3.14159
temperature = -2.5
print(pi * 2)
print(temperature + 10)

Dividing with / always gives a float, even when the result is whole:

Python
print(10 / 2)
print(7 / 2)

Useful number functions

Python
print(abs(-12))          # absolute value: 12
print(round(3.7))        # nearest whole number: 4
print(round(3.14159, 2)) # round to 2 decimal places: 3.14
print(max(4, 9, 2))      # largest: 9
print(min(4, 9, 2))      # smallest: 2
print(pow(2, 5))         # same as 2 ** 5

The floating-point surprise

Python
print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)

Computers store floats in binary, and some decimals (like 0.1) cannot be stored exactly, just as 1/3 cannot be written exactly in decimal. The result is a tiny error. It is not a Python bug; every language behaves this way.

When you compare floats, use round() or math.isclose(), and when you need exact money arithmetic, use the decimal module:

Python
import math
from decimal import Decimal

print(math.isclose(0.1 + 0.2, 0.3))
print(Decimal("0.1") + Decimal("0.2"))

Complex numbers

Python even has complex numbers, written with j, for maths and engineering:

Python
z = 3 + 4j
print(z.real, z.imag, abs(z))
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.