Python Numbers: int, float and Arithmetic Operators
Python has two number types you will use constantly: int for whole numbers and float for numbers with a fractional part. Python integers have no fixed size limit, so 2 ** 100 is computed exactly. Floats follow the standard double-precision format used by almost every computer.
The arithmetic operators
+,-,*add, subtract and multiply./is true division and always returns a float, even for8 / 2(which gives4.0).//is floor division: it divides and rounds down to the nearest whole number.%gives the remainder after floor division.n % 2 == 0is the classic test for an even number.**raises to a power.
Python follows the usual precedence: ** first, then *, /, // and %, then + and -. Use parentheses whenever the order is not obvious to a reader.
Expected output
3.5 3 1 1024 -4 0.30000000000000004 0.3 43.5
Note the fifth line. Floor division rounds toward negative infinity, not toward zero, so -7 // 2 is -4. That surprises people coming from languages that truncate.
Why 0.1 + 0.2 is not 0.3
Floats are stored in binary, and most decimal fractions, including 0.1, have no exact binary form. The tiny representation errors show up as 0.30000000000000004. This is not a Python bug; every language using IEEE 754 doubles behaves the same way. Round results for display with round() or format specifiers, and for money use the decimal module or count whole cents as integers.
Converting between types
int("42") turns text into an integer and float("1.5") into a float. Mixing an int and a float in one calculation gives a float. int(3.9) truncates to 3; use round() when you want the nearest whole number.
Common mistakes
- Expecting
/to return an integer. Use//when you need whole-number division. - Comparing floats with
==. Check that the difference is tiny, for example withmath.isclose(). - Adding a number to text such as
"5" + 3, which raisesTypeError. Convert first.
Summary
intis unlimited in size;floatis an approximate binary fraction./always gives a float;//floors;%is the remainder;**is power.- Floor division rounds toward negative infinity.
- Round floats for display, and avoid floats for exact money.
Quiz: Numbers and math