Float object cannot be interpreted as an integer ошибка

As shown below, range only supports integers:

>>> range(15.0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: range() integer end argument expected, got float.
>>> range(15)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>>

However, c/10 is a float because / always returns a float.

Before you put it in range, you need to make c/10 an integer. This can be done by putting it in int:

range(int(c/10))

or by using //, which returns an integer:

range(c//10)

In Python, we have two data types to represent numeric values

float

and

int

. Float data represent the real numbers, and int data type represents the integer number. There are many operations and functions in Python that only support integer numbers, for example, in list indexing, we can not use float numbers there we always need to pass an int value as an index number.

Similarly, there is a

range()

function in Python that only accepts int values, and if we try to pass a float value to the range() function, we will receive the

TypeError: 'float' object cannot be interpreted as an integer

error.

In this Python guide, we will discuss what this error is and how to debug it. We will also walk through a common example of when many people encounter this error. So without further ado, let’s get started with the error statement.

The Error statement

TypeError: 'float' object cannot be interpreted as an integer

has two parts separated with a colon

:

.

  1. TypeError
  2. ‘float’ object cannot be interpreted as an integer


1. TypeError

TypeError is a standard Python exception. It is raised in a Python program when we try to perform an invalid operation or pass an invalid data type value to a function.


2. ‘float’ object cannot be interpreted as an integer


'float' object cannot be interpreted as an integer

is the error message. This error message tells us that the float variable can not be interpreted as an integer, which simply means the Python interpreter is not able to compute the value of float for the function where it was expecting an integer number. You will encounter this error message in your Python program when you try to pass a floating-point number to the

range()

function.


Example

# float number
num = 6.0

# a list from 0 to 5
my_list = list(range(num))

print(my_list)


Output

Traceback (most recent call last):
    File "main.py", line 5, in <module>
      my_list = list(range(num))
TypeError: 'float' object cannot be interpreted as an integer

The

range()

function accepts an integer value

n

and returns an iterable object from range 0 to

n-1

. In our example, the value of

num

is

6.0

, which is a floating-point number. That’s why the

range(num)

statement returns the Error

TypeError: 'float' object cannot be interpreted as an integer

because it was not able to interpret the 6.0 value as 6.


Solution

To solve the above problem, we can need to convert the 6.0 num value to a 6 num value using

int()

function.

# float number
num = 6.0

# int num
num = int(num)
# a list from 0 to 5
my_list = list(range(num))

print(my_list)


Output

[0,1,2,3,4,5]


Common Example Scenario

Often when we take input from the user using the

input()

function, and if we are expecting a numerical value, we convert that input string value to float using the float function.


Example

students = [{'Rank':1,'Name':'Rahul', "Marks":894},
            {'Rank':2,'Name':'Jay', "Marks":874},
            {'Rank':3,'Name':'Ali', "Marks":870},
            {'Rank':4,'Name':'Rohan', "Marks":869},
            {'Rank':5,'Name':'Kher', "Marks":856},
            {'Rank':5,'Name':'Sofi', "Marks":850},
            ]

# convert the input number to float (error)
top_n = float(input("How many students details do you want to see?: "))

for i in range(top_n):
    print("Rank: ",students[i]['Rank'],"Name: ", students[i]['Name'], "Marks: ", students[i]['Marks'] )


Output

How many students details do you want to see?: 3
Traceback (most recent call last):
   File " main.py", line 12, in <module>
      for i in range(top_n):
TypeError: 'float' object cannot be interpreted as an integer


Error Reason

In the above example in line 10, we are trying to convert the user input value to a floating-point number. And in line 12, we are passing that same floating-point number to the

range()

function, which leading this error.


Solution

If you ever encounter this situation where you need to ask a numeric value from the user using the

input()

function for the

range()

function. There you should always use the

int()

function and convert the user-entered number to an integer value. Because the range() function only accepts integer numbers.

students = [{'Rank':1,'Name':'Rahul', "Marks":894},
            {'Rank':2,'Name':'Jay', "Marks":874},
            {'Rank':3,'Name':'Ali', "Marks":870},
            {'Rank':4,'Name':'Rohan', "Marks":869},
            {'Rank':5,'Name':'Kher', "Marks":856},
            {'Rank':5,'Name':'Sofi', "Marks":850},
            ]

# convert the input number to integer solved
top_n = int(input("How many students details do you want to see?: "))

for i in range(top_n):
    print("Rank: ",students[i]['Rank'],"Name: ", students[i]['Name'], "Marks: ", students[i]['Marks'] )


Output

How many students details do you want to see?: 3
Rank: 1 Name: Rahul Marks: 894
Rank: 2 Name: Jay Marks: 874
Rank: 3 Name: Ali Marks: 870


Conclusion

In this Python tutorial, we learned what

TypeError: 'float' object cannot be interpreted as an integer

error is in Python and how to debug it. The Error is raised when we try to pass a floating-point number to the range() function.

To debug this problem, all we need to do is convert the floating-point number to an integer before we pass it as an argument to the range() function.

If you are still getting this error in your Python program, please share your code in the comment section. We will try to help you in debugging.


People are also reading:

  • Python typeerror: ‘str’ object is not callable Solution

  • Python Iterators

  • Python TypeError: ‘method’ object is not subscriptable Solution

  • Python Generators

  • Python TypeError: ‘function’ object is not subscriptable Solution

  • Python Decorators

  • Python Error: TypeError: ‘tuple’ object is not callable Solution

  • Python ValueError: invalid literal for int() with base 10: Solution

  • Python Closures

  • Python TypeError: ‘NoneType’ object is not callable Solution

Python has two data types that represent numbers: floats and integers. These data types have distinct properties.

If you try to use a float with a function that only supports integers, like the range() function, you’ll encounter the “TypeError: ‘float’ object cannot be interpreted as an integer” error.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

In this guide we explain what this error message means and what causes it. We’ll walk through an example of this error so you can figure out how to solve it in your program.

TypeError: ‘float’ object cannot be interpreted as an integer

Floating-point numbers are values that can contain a decimal point. Integers are whole numbers. It is common in programming for these two data types to be distinct.

In Python programming, some functions like range() can only interpret integer values. This is because they are not trained to automatically convert floating point values to an integer.

This error is commonly raised when you use range() with a floating-point number to create a list of numbers in a given range.

Python cannot process this because Python cannot create a list of numbers between a whole number and a decimal number. The Python interpreter would not know how to increment each number in the list if this behavior were allowed.

An Example Scenario

We’re going to build a program that calculates the total sales of cheeses at a cheesemonger in the last three months. We’ll ask the user how many cheeses they want to calculate the total sales for. We’ll then perform the calculation.

Start by defining a list of dictionaries with information on cheese sales:

cheeses = [
	{ "name": "Edam", "sales": [200, 179, 210] },
	{ "name": "Brie", "sales": [142, 133, 135] },
	{ "name": "English Cheddar", "sales": [220, 239, 257] }
]

Next, we ask the user how many total sales figures they want to calculate:

total_sales = float(input("How many total sales figures do you want to calculate? "))

We convert the value the user inserts to a floating-point. This is because the input() method returns a string and we cannot use a string in a range() statement.

Next, we iterate over the first cheeses in our list based on how many figures the cheesemonger wants to calculate. We do this using a for loop and a range() statement:

for c in range(0, total_sales):
	sold = sum(cheeses[c]["sales"])
	print("{} has been sold {} times over the last three months.".format(cheeses[c]["name"], sold))

Our code uses the sum() method to calculate the total number of cheeses sold in the “sales” lists in our dictionaries.

Print out how many times each cheese has been sold to the console. Our loop runs a number of times equal to how many sales figures the cheesemonger has indicated that they want to calculate.

Run our code and see what happens:

How many total sales figures do you want to calculate? 2
Traceback (most recent call last):
  File "main.py", line 9, in <module>
	for c in range(0, total_sales):
TypeError: 'float' object cannot be interpreted as an integer

Our code asks us how many figures we want to calculate. After we submit a number, our code stops working.

The Solution

The problem in our code is that we’re trying to create a range using a floating-point number. In our code, we convert “total_sales” to a float. This is because we need a number to create a range using the range() statement.

The range() statement only accepts integers. This means that we should not convert total_sales to a float. We should convert total_sales to an integer instead.

To solve this problem, change the line of code where we ask a user how many sales figures they want to calculate:

total_sales = int(input("How many total sales figures do you want to calculate? "))

We now convert total_sales to an integer instead of a floating-point value. We perform this conversion using the int() method.

Let’s run our code:

How many total sales figures do you want to calculate? 2
Edam has been sold 589 times over the last three months.
Brie has been sold 410 times over the last three months.

Our code successfully calculates how many of the first two cheeses in our list were sold.

Conclusion

The “TypeError: ‘float’ object cannot be interpreted as an integer” error is raised when you try to use a floating-point number in a place where only an integer is accepted.

This error is common when you try to use a floating-point number in a range() statement. To solve this error, make sure you use integer values in a range() statement, or any other built-in statement that appears to be causing the error.

You now have the skills and know-how you need to solve this error like a pro!

The Python TypeError: ‘float’ object cannot be interpreted as an integer happens when you pass a float value to a function that needs an integer.

You need to convert the float value into an integer to resolve this error. Let’s see how.

In Python, a float is a data type that represents a decimal number, while an integer is a data type that represents a whole number.

Here are some examples of float and integer values in Python:

# Float values
x = 3.14  # This is a float
y = 0.5  # This is also a float

# Integer values
a = 10  # This is an integer
b = -5  # This is also an integer

If you pass a float where Python expects an integer, the error occurs.

One common situation where this error can occur is when using the range() function in Python.

The range() function is a built-in function that generates a sequence of numbers, and it requires integer arguments to define the range of numbers to generate.

If you try to use a float value as an argument for the range() function, Python will raise a TypeError because it cannot interpret the float value as an integer:

x = 3.5

for i in range(x):  # ❗️TypeError
    print(i)

To solve this error, you need to convert the float value into integer using the int() function:

# 👇 convert float to int
x = int(3.5)

for i in range(x):  # ✅
    print(i)

The float value may also appear as a result of a division operation.

When you use the division operator (/), Python always returns a float value:

x = 10 / 5

print(x)  # 2.0
for i in range(x):  # ❗️TypeError
    print(i)

Even though 10 divided by 5 should return a whole number 2, the division operator in Python is programmed to always return a decimal number.

When you need an integer number, you need to use the floor division operator (//).

See the example below:

x = 10 // 5

print(x)  # 2
for i in range(x):
    print(i)

The floor division operator rounds down the result of the division so that you get a whole number instead of a decimal number.

Finally, you can also use the Python round() function to round a decimal number up or down depending on the closest whole number.

Consider the following example:

x = 2 * 3.4  # 6.8

x = int(x)  # 6
for i in range(x):
    print(i)

The result of 2 * 3.4 is 6.8, but the int() function converts the specified value without considering the floating point number at all. As a result, it always rounds down.

To consider the floating point number, use the round() function instead of the int() function like this:

x = 2 * 3.4  # 6.8

x = round(x)  # 7
for i in range(x):
    print(i)

When you use the round() function, the number can be rounded up when the floating point is .6 or greater.

Conclusion

To conclude, the TypeError: ‘float’ object cannot be interpreted as an integer happens in Python when you try to use a float value in place of an integer, such as when using the range() function.

To fix this error, you need to convert the float value to an integer using the int() or round() functions.

When doing a division, you can also use the floor division operator (//) so that the result is an integer.

By following the examples in this article, you can fix this error in your Python code. 👍

The main reason why Typeerror: float object cannot be interpreted as an integer occurs is using float datatype in the place of int datatype in functions like range(), bin(), etc. Although we can first convert the float value to integer datatype and then use them in these functions to fix this issue.

Typeerror: float object cannot be interpreted as an integer ( Solution multiple scenarios) –

The simplest fix for this issue is typecasting of float datatype to integer datatype. Let’s see this solution in various contexts.

Case 1 : range() function –

range() function accepts only integer values but in case we provide them float datatype , the python interpreter will throw this error.

range(4.5)

"<yoastmark

Solution for range() function scenario –

The easiest solution for this is to typecast float value into an integer one. This is actually a universal solution for float objects that cannot be interpreted as an integer python error.

range(int(4.5))

Case 2: bin() function –

This bin() function returns the binary string for any integer parameter. But when we parametrize any float value in the place of integer value

bin float parameter error

bin float parameter error

Solution – Similar to above, we need to first convert the float to int and then pass it into the bin function.

bin(int(5.5))

Case 3 : chr() function scenario –

chr() function also accepts an integer parameter and converts it into a corresponding character. Let’s see with an example-

chr float parameter error

chr float parameter error
chr(int(71.1))

Case 4 : hex() function –

This function takes an integer and returns the hexadecimal string corresponding for the same.

hex function float parameter error

hex function float parameter error
hex(int(71.1))

The purpose of the above scenario analysis is to understand the root cause for the error float object integer interpretation. Since python is a dynamically type language so typecasting of variables is piece of cake for these scenarios. Still, we miss the same and stuck in such error situations. Hope this article is helpful for you to resolve the same. Please suggest if you need more cases to cover.

Thanks 

Data Science Learner Team

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

We respect your privacy and take protecting it seriously

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

  • Flengine x64 dll ошибка
  • Fldrclnr dll ошибка при загрузке
  • Flatout ultimate carnage ошибка live initialization failed
  • Flatout ultimate carnage xlive dll ошибка
  • Flatout 4 ошибка при установке