Python throws the error, ‘float’ object cannot be interpreted as an integer, when you provide float
value where int
is expected. This happens in case of many built-in functions which needs int
as argument.
Consider this code example –
a = 5.0 b = range(a) # Error: 'float' object cannot be interpreted as an integer
This code will throw the error because range()
expects int
as argument and we are providing float
.
A common mistake happens with division. Single slash ( /
) division returns float
value. So,
5 / 2 = 2.5
When you use this in function like range(5 / 2)
, it will throw error.
To solve this problem, either you can use double slash (//
) division which returns int
value or convert the float
result to int
using int()
function. Check out this code –
print(5 / 2) print(5 // 2) a = range(5 // 2) b = range(int(5 / 2)) # Output: 2.5 # Output: 2
Other built-in functions which also expects int
as argument are –
- bin()
- chr()
- hex()
- range()
- slice()