Sub topic 5
Integers and floats
This chapter covers Python's two main number types, int and float: how to write them, how they are stored, and where they stop behaving like the numbers from school. It assumes you can run a script or the interactive interpreter, use print(), and know that a name is bound to an object (covered in earlier chapters). Arithmetic operators, floating-point comparison, Decimal, and rounding each get their own chapter, so this one only touches them where needed.
Two types, two representations
An int is a whole number with no fractional part. A float is a number stored in a fixed-size binary format that can hold fractions and very large or very small magnitudes. The literal you write decides the type:
print(type(42), type(4.0), type(1e3))
print(1_000_000)
print(0xFF, 0b1010, 0o17)This prints <class 'int'> <class 'float'> <class 'float'>, then 1000000, then 255 10 15.
Three details in that example matter:
4.0is a float even though its value is whole. The decimal point decides the type, not the value.1e3is scientific notation and is always a float. It means 1 × 10³.- Underscores inside a number literal are ignored. They only help you read long numbers.
| Literal | Meaning | Type | Value |
|---|---|---|---|
| `255` | Decimal | int | 255 |
| `0xFF` | Hexadecimal | int | 255 |
| `0b1010` | Binary | int | 10 |
| `0o17` | Octal | int | 15 |
| `2.5e-3` | Scientific | float | 0.0025 |
| `1_000.5` | Underscore separator | float | 1000.5 |
Python has no separate "long" or "short" integer types. There is one int, and there is one float.
Integers have no fixed size
An int grows as needed, limited only by available memory. It does not overflow the way a 32-bit or 64-bit integer does in C or Java.
big = 2 ** 100
print(big)
print(type(big))
print(big.bit_length())The output is 1267650600228229401496703205376, then <class 'int'>, then 101. The bit_length() method returns how many bits the number needs, ignoring the sign.
This is convenient for exact arithmetic, such as factorials, cryptographic keys, and large counters. Large integers are slower than small ones, because Python stores them as arrays of digits and operates on them digit by digit. Operations on small values are fast, but cost grows with the number of digits.
Floats are fixed-size approximations
A Python float is an IEEE 754 double-precision number, the same format as double in C. It uses 64 bits: 1 for the sign, 11 for the exponent, and 52 for the fraction. That gives roughly 15 to 17 significant decimal digits, and a limited range.
import sys
print(sys.float_info.max)
print(sys.float_info.epsilon)
print(1e308 * 10)This prints 1.7976931348623157e+308, then 2.220446049250313e-16, then inf. The three lines show:
maxis the largest finite float.epsilonis the gap between1.0and the next representable float. It is the best relative precision you get.- Multiplying past the maximum does not raise an error. It produces
inf, meaning infinity.
Because the format is binary, most decimal fractions such as 0.1 cannot be stored exactly. The float holds the nearest representable value. A later chapter explains this fully, along with math.isclose and Decimal. For now, treat float results as approximate.
Special values: inf and nan
Floats include two special values besides ordinary numbers. inf is infinity, and nan ("not a number") is the result of an undefined operation.
inf = float("inf")
nan = float("nan")
print(inf > 10 ** 100)
print(inf - inf)
print(nan == nan)
print(nan != nan)The output is True, nan, False, True. The last two lines are the surprising part. nan is not equal to anything, including itself. To test for it, use math.isnan(x), not x == nan.
Mixing ints and floats
When an int and a float meet in arithmetic, Python converts the int to a float and the result is a float.
print(1 + 2.0)
print(type(1 + 2.0))
print(2 ** 53 == float(2 ** 53))
print(2 ** 53 + 1 == float(2 ** 53 + 1))
print(float(2 ** 53 + 1))This prints 3.0, <class 'float'>, True, False, and 9007199254740992.0.
The last three lines show a limit. A float has 53 bits of precision in its fraction (including an implicit leading bit), so above 2⁵³ it cannot represent every integer. float(2 ** 53 + 1) rounds to 9007199254740992.0. Python compares an int and a float by their exact values, so the original integer 9007199254740993 is not equal to that float, and the comparison is False.
The OverflowError branch is real. Converting an integer beyond the float range fails instead of returning inf:
try:
print(10 ** 400 + 1.0)
except OverflowError as e:
print("OverflowError:", e)This prints OverflowError: int too large to convert to float. Compare that with 1e308 * 10, which gives inf. The difference is the operation: float arithmetic saturates to inf, while converting a huge int raises an error.
Useful methods on numbers
Numbers are objects, so they have methods. A literal integer needs parentheses or a space before the dot, because 5. would be read as a float. Floats are usually written in parentheses too.
print((2.5).is_integer())
print((3.0).is_integer())
print((0.5).as_integer_ratio())
print((255).bit_length())The output is False, True, (1, 2), and 8. is_integer() tells you whether a float has no fractional part. as_integer_ratio() returns the exact fraction the float stores, which is a useful way to see float approximation: (0.1).as_integer_ratio() returns (3602879701896397, 36028797018963968), not (1, 10).
Choosing between int and float
Use these criteria:
- Use
intfor counts, indexes, identifiers, and anything that is naturally whole. Results are exact at any size. - Use
floatfor measurements, ratios, and scientific values, where small relative error is acceptable and the range is wide. - Do not use
floatfor money or other values where decimal digits must be exact. UseDecimal, covered in a later chapter. - Do not store large identifiers, such as 19-digit IDs, in a float. Above 2⁵³ they lose digits silently.
Common errors
- Assuming
1e3is an int. It is a float.range(1e3)raisesTypeError; userange(1000). - Comparing with
nan.x == float("nan")is alwaysFalse. Usemath.isnan. - Expecting overflow wraparound. Integers never wrap. If a calculation grows without bound, memory and time grow instead.
- Writing a leading zero.
007is aSyntaxErrorin Python 3. Octal needs the0oprefix. - Trusting float equality.
0.1 + 0.2 == 0.3isFalse. Compare with a tolerance, as a later chapter shows.
Exercise
Without running it, predict the output of these three lines, then explain the third: print(type(2 * 3.0)), print(float("inf") == float("inf")), print(float(2 ** 53 + 1) == 2 ** 53 + 1).
Show answer
The first line prints <class 'float'>, because multiplying an int by a float produces a float (6.0). The second prints True, because two infinities compare equal (unlike nan). The third prints False. The integer 2 ** 53 + 1 is 9007199254740993, but float(...) rounds it to 9007199254740992.0. Python compares an int and a float by exact value, and those two values differ by 1.
Exercise
A script stores a 20-digit order ID as order_id = float(12345678901234567890) and later prints int(order_id). Will the printed number match the original? Why or why not?
Show answer
It will not match. A float keeps only about 15 to 17 significant decimal digits (53 bits of precision), so a 20-digit integer is rounded to the nearest representable float. int(order_id) returns that rounded value, which differs from 12345678901234567890 in the low digits. Keep identifiers as int (or str) to avoid this loss.