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.
Before this lesson: Python Data Types, Python Operators
2Python Numbers: diagram
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.
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.
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.
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.
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.
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.
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.
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, orDecimal. - Text that looks like a number, such as
"42": it is a string until you convert it.
Quick reference: Python Numbers
- Python Division (/) vs Floor Division (//) — `/` is **true division** and always returns a float (`7 / 2` is `3.5`), while `//` is **floor division** and …
- How to Convert a String to an Int in Python — Use `int(text)`, for example `int("42")` returns `42`. If the string is not a whole number, such as `"3.7"` o…
- How to Convert an Int to a String in Python — Use `str(number)`, for example `str(42)` returns `"42"`. For formatting such as padding or commas, use an [f-…
- How to Convert a String to a Float in Python — Use `float(text)`, for example `float("3.14")` returns `3.14`. Text that is not a number, such as `"abc"` or …
- How to Convert a Float to an Int in Python — `int(3.9)` returns `3` because it cuts off the decimal part. Use `round(3.9)` to get `4`, or `math.floor()` a…
- How to Pad a Number with Leading Zeros in Python — Use an f-string: `f"{7:03d}"` gives `'007'`. For text that is already a string, `"7".zfill(3)` gives the same…
- Python Program to Calculate the Average of a List — The average of a list is the sum divided by the count: `sum(numbers) / len(numbers)`.
- Python BMI Calculator Program — A BMI calculator computes `weight_kg / height_m ** 2` and uses `if/elif` to name the category: below 18.5 und…
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.
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.
- Line 1-2
billis afloatbecause it has a decimal point, andpeopleis anint. - Line 3
/always gives a float, soshareis21.6125even if the numbers had divided exactly. - Line 4The f-string
{share:.2f}shows the number with two decimals, rounded to21.61. The variable itself is unchanged. - Line 5Multiplying by 100 and calling
round()turns dollars into a whole number of cents (8645). Whole cents avoid float rounding problems. - Line 6
divmod(cents, people)returns the quotient and remainder together, soeachis 2161 andextrais 1. - Line 7Everyone pays 2161 cents and one cent is left over, because 4 does not divide 8645 evenly.
- Line 8
:,.2fcombines a thousands separator with two decimals, andbill * 1.15adds a 15 percent tip. - Line 9
type()confirms the kinds:billis afloat,peopleanint, andround()with one argument returns anint.
8Python Numbers: common mistakes
Comparing floats with ==
✗ Wrong
total = 0.1 + 0.2
print(total == 0.3)✓ 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)✓ 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")✓ 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])✓ 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)✓ 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 ✓ CompletedWrite 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().
def to_hours_minutes(total_minutes):
# return (hours, minutes)
pass
print(to_hours_minutes(135))
def to_hours_minutes(total_minutes):
return divmod(total_minutes, 60)
print(to_hours_minutes(135))
2. Predict the division results
Predict the output Easy ✓ CompletedDivision and rounding have a few surprises. Type exactly what the program prints.
print(7 // 2, 7 % 2)
print(-7 // 2, -7 % 2)
print(type(6 / 3))
print(round(2.5), round(3.5))
3 1
-4 1
<class 'float'>
2 4
2 more exercises → 6 more examples
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