Python Tutorial · Python Basics · Lesson 7 of 42

Python Numbers

Integers, floats, arithmetic and why 0.1 + 0.2 isn't exactly 0.3.

int and float

int holds whole numbers of any size; float holds decimal numbers.

Example 1Try it yourself
a = 10
b = 2.5
big = 2 ** 100
print(type(a), type(b))
print(big)

Output

<class 'int'> <class 'float'>
1267650600228229401496703205376

Arithmetic operators

Example 2Try it yourself
print(7 + 2)
print(7 - 2)
print(7 * 2)
print(7 / 2)   # true division
print(7 // 2)  # floor division
print(7 % 2)   # remainder
print(7 ** 2)  # power

Output

9
5
14
3.5
3
1
49

Note the difference between / (always returns a float) and // (floor division).

Floating-point precision

Floats are stored in binary, so some decimals can't be represented exactly:

Example 3Try it yourself
import math
print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)
print(math.isclose(0.1 + 0.2, 0.3))
print(round(2.675, 2))

Output

0.30000000000000004
False
True
2.67

Compare floats with math.isclose(), and use the decimal module (or integer cents) for money.

Test yourself

What does 7 // 2 evaluate to?

  1. 3.5
  2. 3
  3. 4
  4. 1
Show answer

Answer: 3