Error guide · TypeError
TypeError: 'float' object cannot be interpreted as an integer
range() was given a decimal number, but it needs a whole number.
Example
n = 5 / 2 for i in range(n): print(i)
What Python says
TypeError: 'float' object cannot be interpreted as an integer
As printed by Python 3.12. Other versions may word it slightly differently.
Why it happens
The division operator / always gives a float, even when the answer looks whole: 10 / 2 is 5.0. range() counts in whole steps, so it refuses 2.5 and also 5.0. Use // for whole-number division, or convert with int().
How to fix it
n = 5 // 2 for i in range(n): print(i)
Output: 0 ⏎ 1
Tips
- Use
//when you need a whole-number result. - Convert with
int(n)only when cutting off the decimal part is what you want. - Positions in lists and strings must also be whole numbers.