BasicsChapter 10 of 114
Numbers
Integers, floats, the two kinds of division, and why 0.1 + 0.2 misbehaves.
int and float
An int is a whole number. A float has a decimal point. Writing the point is what makes the difference:
whole = 7
decimal = 7.0
print(type(whole), type(decimal))Output
<class 'int'> <class 'float'>
Python integers have no size limit. They grow to fit:
print(2 ** 100)Output
1267650600228229401496703205376
Arithmetic
print(7 + 3)
print(7 - 3)
print(7 * 3)
print(7 / 3)Output
10 4 21 2.3333333333333335
Note the last one: / always gives a float, even when the division is exact.
print(6 / 3)
print(type(6 / 3))Output
2.0 <class 'float'>
Floor division and remainder
// divides and throws away the fraction. % gives what is left over:
print(7 // 3)
print(7 % 3)
print(-7 // 3)
print(-7 % 3)Output
2 1 -3 2
% is the usual way to ask "is this even?" or "every nth time":
for n in range(6):
if n % 2 == 0:
print(n, "is even")Output
0 is even 2 is even 4 is even
Powers
print(3 ** 2)
print(2 ** 0.5)Output
9 1.4142135623730951
Rounding
print(round(3.7))
print(round(3.14159, 2))Output
4 3.14
print(round(0.5), round(1.5), round(2.5))Output
0 2 2
Floats are approximations
A float is stored in binary, and some decimal fractions have no exact binary form. The result is the most reported "bug" in every language that uses them:
print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)Output
0.30000000000000004 False
Nothing is broken. 0.1 was never exactly a tenth. Compare with a tolerance instead of ==:
from math import isclose
print(isclose(0.1 + 0.2, 0.3))Output
True
For money, use decimal, which counts in base ten:
from decimal import Decimal
print(Decimal("0.1") + Decimal("0.2"))Output
0.3
Readable long numbers
Underscores in a numeric literal are ignored, so you can group digits:
population = 8_100_000_000
print(population)Output
8100000000
Test yourself
3 questionsWhat is 7 / 2?
Show the answer
3.5 — A single slash always produces a float. Use // if you want the whole number 3.
Why is 0.1 + 0.2 == 0.3 False?
Show the answer
Floats are binary approximations, so 0.1 was never exactly a tenth — Compare with math.isclose, or use decimal.Decimal when the answer has to be exact.
What is -7 // 3?
Show the answer
-3 — Floor division rounds down rather than towards zero, which keeps it consistent with %.
Casting
Converting between types on purpose, and where conversion fails.