Numbers
int and float — whole numbers and decimals.
3 minute read
Big idea
Python has two everyday kinds of number: int for whole numbers and float for numbers with a decimal point.
The idea
apples = 12 # int
price = 0.45 # float
temp = -3 # int — negatives are fine
type() tells you what kind of value something is:
print(type(12))
print(type(0.45))
print(type(12.0))output
<class 'int'>
<class 'float'>
<class 'float'>Run and edit it in the app.
12.0 is a float even though it's a whole number — the decimal point decides.
ints never overflow
In C an int has a maximum. A Python int just grows as big as it needs to:
print(2 ** 100)output
1267650600228229401496703205376Run and edit it in the app.
(** means "to the power of" — more on operators soon.)
Division always gives a float
/ always gives a float, even when it divides exactly. For a whole-number answer, use //:
print(10 / 2)
print(7 / 2)
print(7 // 2)What does it print? Show the answer
5.0
3.5
3Run and edit it in the app.
Floats are close, not exact
A float stores its digits in binary, and most decimals (like 0.1) can't be written exactly in binary — the way 1/3 can't be written exactly in decimal. Tiny errors creep in:
print(0.1 + 0.2)
print(round(0.1 + 0.2, 2))output
0.30000000000000004
0.3Run and edit it in the app.
That's not a Python bug; every language does it. round(x, 2) rounds to 2 decimal places when you need to show a tidy answer. For money, programmers often count in whole cents with ints.
Watch it
Handy number tools
abs(-7)→7— distance from zero.round(3.14159, 2)→3.14.max(3, 9, 4)→9,min(3, 9, 4)→3.- Underscores make big numbers readable:
1_000_000is one million.
total = 10
count = 4
print(total // count)output
2.5Run and edit it in the app.
What does print(9 / 3) show?
Think of it like
ints are counting on your fingers — always exact. floats are a measuring tape — great for lengths, but the last tiny fraction is always a little fuzzy.
Key terms
- int — A whole number, any size.
- float — A number with a decimal point; stored approximately.
- type() — Tells you the kind of a value.
Check yourself
What type is 5.0?
What does 7 // 2 give?
Why does 0.1 + 0.2 print 0.30000000000000004?