‘float’ object cannot be interpreted as an integer – Python Error

Total
0
Shares

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

    Tweet this to help others

Other built-in functions which also expects int as argument are –

  • bin()
  • chr()
  • hex()
  • range()
  • slice()

Sign Up for Our Newsletters

Get only the best articles delivered to your mail

You May Also Like

Convert list to string in Python

Table of Contents Hide Joining with delimiterJoining integer itemsUsing map() functionUsing lambda functionUsing LoopsLive DemoRelated Posts: Python provides join() function which could be used to convert list to string. If…
View Post