Python Numbers
Beginner Python Basics

Python Numbers

1Python Numbers: overview

Python has three built-in number types, int for whole numbers, float for decimal numbers and complex for numbers with an imaginary part, and each follows its own rules for size, division and precision.

GoalBy the end you can tell int, float and complex apart, write readable number literals, use //, %, ** and divmod, round and format results, and avoid the 0.1 + 0.2 float trap.

Before this lesson: Python Data Types, Python Operators

2Python Numbers: diagram

Python number typesPython number typestypeexampleuse it forint42 1_000_000counts, whole numbersfloat3.14 2.5e3measurements, averagescomplex3 + 4jengineering, science7 / 2 is always a float (3.5). 7 // 2 stays an int (3).
Most programs use int and float. The / operator always produces a float, while // keeps whole numbers whole.

3Python Numbers: explained step by step

Python has three built-in kinds of number: int for whole numbers, float for numbers with a decimal point, and complex for numbers with an imaginary part. In everyday programs you will use int and float almost all the time, so this lesson concentrates on them: how they behave, where they surprise you, and how to display them neatly.

Integers have no size limit

An int is a whole number, positive, negative or zero. Unlike many languages, Python integers can be as big as your memory allows, so you never get an overflow. For readability you can put underscores inside a long literal; Python ignores them.

Python
population = 8_100_000_000
print(population)
print(type(population))
print(2 ** 100)

You can also write integers in other bases: 0b1010 is binary, 0o17 is octal and 0xFF is hexadecimal. bin(), oct() and hex() convert the other way.

Python
print(0b1010, 0o17, 0xFF)
print(bin(10), hex(255))

Floats are numbers with a decimal point

A float is any number written with a . or in scientific notation such as 1.5e3 (which means 1.5 x 10^3). Dividing with / always gives a float, even when the answer looks whole. This surprises many beginners, and it matters when you later try to use that value as a count or an index.

Python
print(7 / 2)
print(8 / 2)
print(type(8 / 2))
print(1.5e3, 2e-3)

Mixing an int and a float in one calculation gives a float. Converting between types is covered in Python casting, and the basic types are introduced in Python data types.

Floor division, remainder and divmod

Besides /, there are two operators that work with whole-number division, described in Python operators:

  • // is floor division: how many times does it fit, rounded down.
  • % is the modulo (remainder): what is left over.

divmod(a, b) returns both at once, which is handy for converting minutes into hours and minutes.

Python
minutes = 135
hours = minutes // 60
left = minutes % 60
print(hours, left)
print(divmod(minutes, 60))
print(-7 // 2, -7 % 2)

Notice that floor division rounds towards minus infinity, so -7 // 2 is -4, not -3. And ** raises to a power: 3 ** 2 is 9.

Built-in helpers: abs, round, min, max and sum

Several functions work on numbers without any import: abs() removes the sign, round() rounds, and min(), max() and sum() work on a list of numbers. More tools live in the math module, covered in Python math and statistics.

Python
temps = [18.5, 21.0, 19.25, 23.5]
print(abs(-12), min(temps), max(temps))
print(sum(temps) / len(temps))
print(round(3.14159, 2), round(2.5), round(3.5))

round() with one argument gives an int. It rounds halves to the nearest even number (called banker's rounding), so round(2.5) is 2 and round(3.5) is 4. This is correct behaviour, not a bug.

Why 0.1 + 0.2 is not exactly 0.3

Computers store floats in binary, and a number like 0.1 cannot be stored exactly, just as 1/3 cannot be written exactly in decimals. The tiny error shows up in the results.

Python
total = 0.1 + 0.2
print(total)
print(total == 0.3)
print(round(total, 2) == 0.3)

So never compare floats with ==. Use round() first, or better, math.isclose(a, b), which checks that two numbers are close enough. For money, where exact cents matter, use the Decimal type or store whole cents as integers.

Formatting numbers with f-strings

Often you only want to display a number nicely. In an f-string, :.2f shows two decimals and :, adds thousands separators. The number itself is not changed. More formatting tricks appear in Python input and output.

Python
price = 1234.5
print(f"Price: {price:.2f}")
print(f"Price: {price:,.2f}")
print(f"Views: {2500000:,}")

Complex numbers in one paragraph

A complex number has a real and an imaginary part, written with a j, like 3 + 4j. They are used in engineering and science and are rare in beginner code. If you need one, abs(3 + 4j) gives its size, 5.0.

Which number type should I use?

  • Counts, positions and anything you cannot split: int.
  • Measurements and averages: float, and format them when you display them.
  • Money: whole cents as int, or Decimal.
  • Text that looks like a number, such as "42": it is a string until you convert it.

Quick reference: Python Numbers

4Python Numbers: syntax

count = 1_000_000          # int (underscores are ignored)
mask = 0b1010              # binary literal; 0o17 octal; 0xFF hex
price = 19.99              # float
big = 1.5e3                # scientific notation = 1500.0
z = 3 + 4j                 # complex

7 / 2                      # 3.5   true division (always float)
7 // 2                     # 3     floor division
7 % 2                      # 1     remainder (modulo)
divmod(7, 2)               # (3, 1)
2 ** 10                    # 1024  power

abs(-5)  round(3.14159, 2)  min(a, b)  max(a, b)  sum(list)
f"{price:.2f}"  f"{count:,}"   # 2 decimals / thousands separators

5Python Numbers: run the example

Press Run (or Ctrl + Enter). The output (step 6) appears directly below the code. Change anything and run it again.

Interactive example
bill = 86.45
people = 4
share = bill / people
print(f"Each pays {share:.2f}")
cents = round(bill * 100)
each, extra = divmod(cents, people)
print(each, "cents each,", extra, "cent left over")
print(f"Bill with tip: {bill * 1.15:,.2f}")
print(type(bill), type(people), type(cents))
Expected outputEach pays 21.61
2161 cents each, 1 cent left over
Bill with tip: 99.42
<class 'float'> <class 'int'> <class 'int'>

7Python Numbers: how the example works

Hover or tap a step to highlight its lines in the example above.

  1. Line 1-2bill is a float because it has a decimal point, and people is an int.
  2. Line 3/ always gives a float, so share is 21.6125 even if the numbers had divided exactly.
  3. Line 4The f-string {share:.2f} shows the number with two decimals, rounded to 21.61. The variable itself is unchanged.
  4. Line 5Multiplying by 100 and calling round() turns dollars into a whole number of cents (8645). Whole cents avoid float rounding problems.
  5. Line 6divmod(cents, people) returns the quotient and remainder together, so each is 2161 and extra is 1.
  6. Line 7Everyone pays 2161 cents and one cent is left over, because 4 does not divide 8645 evenly.
  7. Line 8:,.2f combines a thousands separator with two decimals, and bill * 1.15 adds a 15 percent tip.
  8. Line 9type() confirms the kinds: bill is a float, people an int, and round() with one argument returns an int.

8Python Numbers: common mistakes

Comparing floats with ==

✗ Wrong

total = 0.1 + 0.2
print(total == 0.3)
No error, but it prints False because total is 0.30000000000000004

✓ Right

import math
total = 0.1 + 0.2
print(math.isclose(total, 0.3))

Floats are stored in binary, so many decimals are slightly off. Compare with math.isclose() or round both sides first.

Adding a number to a string

✗ Wrong

items = 5
print("Items: " + items)
TypeError: can only concatenate str (not "int") to str

✓ Right

items = 5
print(f"Items: {items}")

+ cannot join text and a number. Use an f-string, or pass the pieces to print() separately.

Converting a decimal string with int()

✗ Wrong

price = int("3.5")
ValueError: invalid literal for int() with base 10: '3.5'

✓ Right

price = int(float("3.5"))
print(price)

int() only accepts whole-number text. Convert to float first, then to int if you need to drop the decimals.

Using the result of / as a list index

✗ Wrong

items = ["a", "b", "c", "d"]
middle = len(items) / 2
print(items[middle])
TypeError: list indices must be integers or slices, not float

✓ Right

items = ["a", "b", "c", "d"]
middle = len(items) // 2
print(items[middle])

/ always returns a float, even for 4 / 2. Use floor division // to get an int.

Typing commas in a big number

✗ Wrong

population = 1,000,000
print(population)
No error, but it prints (1, 0, 0): Python made a tuple of three numbers

✓ Right

population = 1_000_000
print(population)

Commas separate values, they do not group digits. Use underscores for readability, or no separators at all.

9Python Numbers: exercises

Write your answer, then press Check. The checks run in your browser.

1. Minutes to hours and minutes

Write code Easy

Write a function to_hours_minutes(total_minutes) that returns a tuple (hours, minutes). For example to_hours_minutes(135) returns (2, 15). Use // and % or divmod().

Your code
def to_hours_minutes(total_minutes):
    # return (hours, minutes)
    pass

print(to_hours_minutes(135))

2. Predict the division results

Predict the output Easy

Division and rounding have a few surprises. Type exactly what the program prints.

Read this code
print(7 // 2, 7 % 2)
print(-7 // 2, -7 % 2)
print(type(6 / 3))
print(round(2.5), round(3.5))

2 more exercises → 6 more examples

Finished this lesson?
Progress is saved in this browser — create a free account to keep it across devices.

Questions learners ask

Why does Python say 0.1 + 0.2 is 0.30000000000000004?

Computers store floats in binary, and 0.1 and 0.2 cannot be written exactly in binary, just as 1/3 cannot be written exactly in decimals. The result is very slightly off. Compare floats with math.isclose(), format them with :.2f for display, and use Decimal or whole cents for money.

What is the difference between / and // in Python?

/ is true division and always returns a float: 7 / 2 is 3.5 and 8 / 2 is 4.0. // is floor division: it rounds the result down to a whole number, so 7 // 2 is 3 and -7 // 2 is -4. Use // when you need a count or an index.

Is there a maximum integer in Python?

No. Python ints grow as large as your memory allows, so 2 ** 1000 works without overflow. Floats are different: they have a limited range and precision of about 15 to 17 significant digits.

Further reading

10Next lesson

Up nextPython CastingCasting converts a value from one type to another, such as the text "42" to the integer 42, by calling the target type …

Related:
Python Data TypesPython CastingPython OperatorsPython math and statistics

← Python Data Types · All Python Basics lessons · Practise in the IDE