Python Numbers
Python numbers come in three built-in types: int for whole numbers, float for numbers with a decimal point, and complex for numbers with an imaginary part. Python creates the right type automatically based on how you write the value.
int, float and complex
a = 25 # int
b = 2.5 # float
c = 3 + 4j # complex
big = 10 ** 30 # ints can be as large as you like
print(type(a), type(b), type(c))
print(big)
print(1_000_000 + 1)<class 'int'> <class 'float'> <class 'complex'> 1000000000000000000000000000000 1000001
Python integers have no fixed size limit, so 10 ** 30 works without overflow. Underscores inside a number, as in 1_000_000, are ignored and simply make long numbers easier to read.
Division in Python
Python has two division operators. A single slash always returns a float. A double slash performs floor division and drops the fractional part. The % operator gives the remainder.
print(7 / 2)
print(7 // 2)
print(7 % 2)
print(divmod(17, 5))3.5 3 1 (3, 2)
Rounding Numbers
round() rounds to a given number of decimal places. Note that floats are stored in binary, so some decimals cannot be represented exactly. That is why 0.1 + 0.2 is not exactly 0.3.
price = 19.98765
print(round(price, 2))
print(round(7.5))
print(0.1 + 0.2)
print(round(0.1 + 0.2, 2))19.99 8 0.30000000000000004 0.3
The math Module
For more advanced maths, import the math module from the standard library. It provides square roots, powers, rounding up and down, constants like pi, and much more.
import math
print(math.sqrt(81))
print(math.ceil(4.1))
print(math.floor(4.9))
print(round(math.pi, 4))
print(abs(-12), max(3, 9, 4), min(3, 9, 4))9.0 5 4 3.1416 12 9 3
Random Numbers
The random module generates random numbers. Each run gives different results, unless you set a seed, which makes the sequence repeatable. That is handy for testing.
import random
random.seed(1)
print(random.randint(1, 6))
print(random.choice(["rock", "paper", "scissors"]))2 scissors
Frequently asked questions
How do I round to 2 decimal places in Python?
Use round(value, 2) to get a rounded number, or an f-string like f"{value:.2f}" to display it with exactly two decimals.
Why does 0.1 + 0.2 not equal 0.3 in Python?
Floats are stored in binary and many decimal fractions cannot be stored exactly. Use round(), math.isclose() or the decimal module when you need exact decimal results, such as for money.
What is the difference between / and // in Python?
The / operator always returns a float with the full result. The // operator performs floor division, rounding down to the nearest whole number.
How do I generate a random number in Python?
Import the random module and call random.randint(a, b) for a whole number between a and b inclusive, or random.random() for a float between 0 and 1.