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.
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
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!
In this article, we will learn about the TypeError: ‘float’ object can not be interpreted as an integer.
This error will occur in all the functions or methods. Where the function or method accepts only the integer value as a parameter. But instead, we have passed float values. The most common example is the range function. Since the range function only accepts an integer as a parameter.
For example, when we divide 16 by 8 using division operator ‘/’ in python, it’ll return a float value i.e. 2.0 and not an integer. This raises an error when we want an int as a parameter, but we have a float value.

Let us understand it more with the help of an example.
Example 1:
for i in range(3.0):
print(i)
print('end of loop')
Output:
File "float.py", line 1, in <module>
for i in range(3.0):
TypeError: 'float' object cannot be interpreted as an integer
In the above example, we did not perform any arithmetic operations. Instead, we passed a float value as a range parameter. In this case, the cause for the TypeError is that the range function does not take float value as a parameter.
Solution:
for i in range(3):
print(i)
print('end of loop')
Output:
0
1
2
end of loop
Example 2:
for i in range(16/8):
print(i)
print('end of loop')
Output:
Traceback (most recent call last):
File "pyprogram.py", line 1, in <module>
for i in range(16/8):
TypeError: 'float' object cannot be interpreted as an integer
In the above example, when we performed division operation inside the range() function. We got a float value (2.0). But the range function takes only an integer value as a parameter.
Thus the error “TypeError: ‘float’ object cannot be interpreted as an integer” is encountered.
Solution:
for i in range(5//8):
print(i)
print('end of loop')
Output:
0
1
end of loop
Unlike the division operator ‘/’ the floor division operator ‘//’ in python, returns an integer value. The floor division operator removes the digits after the decimal point. Thus we get an integer value.
So on dividing 16 by 8 using floor division operator ‘//’ we get ‘2’ as a parameter in range function. Thus no error is encountered, and we get the desired output.
Hi Guys,
I am trying to use the range function in my code. But it is showing me the below error.
TypeError Traceback (most recent call last)
<ipython-input-13-a83306d87fcd> in <module>
1 # floats with python range
----> 2 for i in range(0.1, 0.5, 0.1):
3 print(i)
TypeError: 'float' object cannot be interpreted as an integer
How can I solve this error?

Jun 29, 2020
in Python
by
• 38,240 points
•
15,510 views
2 answers to this question.
Hi@akhtar,
The range function does not work with floats. Only integer values can be specified as the start, stop, and step arguments. But you can use this in a different way. I have attached one example for your reference.
def range_with_floats(start, stop, step):
while stop > start:
yield start
start += step
for i in range_with_floats(0.1, 0.5, 0.1):
print(i)
I hope this will help you.
![]()
answered
Jun 29, 2020
by
MD
• 95,420 points
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.
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.
![]()
answered
Dec 16, 2020
by
Gitika
• 65,910 points
Related Questions In Python
Table of Contents
Hide
- What is TypeError: ‘numpy.float64’ object cannot be interpreted as an integer?
- How to Fix TypeError: ‘numpy.float64’ object cannot be interpreted as an integer?
- Method 1: Using the astype() function
- Method 2: Using the int() function
- Conclusion
The TypeError: ‘numpy.float64’ object cannot be interpreted as an integer occurs if you pass a float value to a function like range() which accepts only integer.
In this tutorial, let us look at what is TypeError: ‘numpy.float64’ object cannot be interpreted as an integer and how to resolve this error with examples.
The TypeErrors are very common in Python, and usually, we get if we pass the wrong data type to a function.
The range() function expects an integer. However, while working with NumPy arrays, it is common that sometimes we pass a float value into the range() function and get a TypeError.
Let us take an example to reproduce this error in Python.
# import numpy library
import numpy as np
# create array of values in pandas
my_array = np.array([2.5, 6.4, 2.1, 7.4, 8.9, 1.1])
# print the range of values using for loop
for i in range(len(my_array)):
print(range(my_array[i]))
Output
Traceback (most recent call last):
File "C:PersonalIJSCodeprogram.py", line 10, in <module>
print(range(my_array[i]))
TypeError: 'numpy.float64' object cannot be interpreted as an integer
How to Fix TypeError: ‘numpy.float64’ object cannot be interpreted as an integer?
There are two ways to fix the TypeError.
- Using astype() method
- Using int() method
Let us take a look at both methods with examples.
Method 1: Using the astype() function
The astype() method comes in handy when we have to convert one data type into another data type.
We can fix our code by converting the values of the NumPy array to an integer using the astype() method, as shown below.
# import numpy library
import numpy as np
# create array of values in pandas
my_array = np.array([2.5, 6.4, 2.1, 7.4, 8.9, 1.1])
# covert values of array to integer using astype()
my_array = my_array.astype(int)
print("Converted array is", my_array)
# print the range of values using for loop
for i in range(len(my_array)):
print(range(my_array[i]))
Output
Converted array is [2 6 2 7 8 1]
range(0, 2)
range(0, 6)
range(0, 2)
range(0, 7)
range(0, 8)
range(0, 1)
Method 2: Using the int() function
Another way to fix the issue is to cast the array object to an integer using the int() method before getting into range.
The int() method will convert each float value to an integer in the NumPy array, thus avoiding the TypeError.
# import numpy library
import numpy as np
# create array of values in pandas
my_array = np.array([2.5, 6.4, 2.1, 7.4, 8.9, 1.1])
# print the range of values using for loop
for i in range(len(my_array)):
# cast to integer before applying the range
print(range(int(my_array[i])))
Output
range(0, 2)
range(0, 6)
range(0, 2)
range(0, 7)
range(0, 8)
range(0, 1)
Conclusion
If you pass a float value to functions like range() which can only accept integer Python will raise TypeError: ‘numpy.float64’ object cannot be interpreted as an integer
There are two ways to fix this TypeError.
- We can use
astype()method to convert the values of the NumPy array to an integer - We can cast the array object to an integer using the
int()method before getting into range.
Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.
Sign Up for Our Newsletters
Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.
By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.
Вы хотите узнать, как генерировать диапазон чисел с плавающей запятой в Python? В этом руководстве вы найдете много способов получения значений с плавающей запятой в пределах заданного диапазона.

Мы рекомендуем вам по крайней мере использовать Python 3 для написания кода и запуска примеров. Python 2.x все еще получает обновления, но более новые версии более стабильны и продвинуты.
Чего Не Хватает В Функции Диапазона Python?
Диапазон Python может генерировать только набор целых чисел из данной полосы. Он также не допускает параметр типа с плавающей запятой и не может генерировать диапазон чисел с плавающей запятой.
Он принимает один, два или три параметра (старт / стоп / шаг). Однако все аргументы имеют целочисленный тип. Если вы передадите float, это приведет к ошибке TypeError.
start = 1
stop = 6.7
step = 0.1
for value in range(start, stop, step):
print (value)
Когда вы запускаете приведенный выше код, он выдает следующую ошибку:
TypeError: 'float' object cannot be interpreted as an integer
Приведенный выше пример предполагает, что Python не предоставляет встроенного способа генерации диапазона с плавающей запятой. Поэтому нам нужно разработать собственную реализацию функции range.
Почему Python range() не работает с float?
Функция range генерирует конечный набор целых чисел. Вы можете определить размер, вычитая начальное значение из конечного значения (когда шаг = 1). Ниже приведена общая формула для расчета длины.
(stop - start) //step + 1
Проверьте примеры приведенные ниже, чтобы получить ясность.
>>> len(list(range(1,10,2))) 5 >>> 10-1/2 + 1 >>> (10-1)//2 + 1 5
Однако тот же диапазон фактически имеет бесконечное количество из чисел с плавающей запятой. Вы можете ограничить его, используя фиксированное значение точности. Следовательно, это может быть возможной причиной того, что range() не позволяет работать с float.
Использование Yield для генерации диапазона с плавающей запятой
Вы можете написать пользовательскую функцию Python, как показано ниже. Это может позволить вам указать значение с плавающей запятой для аргумента шага.
import decimal
def float_range(start, stop, step):
while start < stop:
yield float(start)
start += decimal.Decimal(step)
print(list(float_range(0, 1, '0.1')))
Вывод следующий:
[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
Мы использовали модуль decimal для сохранения точности.
Функция NumPy Arange() для диапазона значений с плавающей запятой
Чтобы использовать функцию arange(), вам необходимо установить и импортировать пакет numpy. Эта библиотека имеет различные арифметические и числовые функции для генерации массивов / матриц разных размеров.
В любом случае, здесь мы будем использовать функцию arange() для генерации диапазона чисел с плавающей запятой.
Arange() имеет ту же сигнатуру, что и встроенный метод range. Но мы можем передать аргументы типа float (с плавающей запятой) в качестве параметров этой функции.
# Syntax import numpy arange(start, stop, step)
Теперь давайте рассмотрим пример, чтобы улучшить наше понимание.
from numpy import arange
print("Float range using NumPy arange():")
print("nTest 1:")
for i in arange(0.0, 1.0, 0.1):
print(i, end=', ')
print("nnTest 2:")
for i in arange(0.5, 5.5, 0.5):
print(i, end=', ')
print("nnTest 3:")
for i in arange(-1.0, 1.0, 0.5):
print(i, end=', ')
Вывод следующий:
Float range using NumPy arange(): Test 1: 0.0, 0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6000000000000001, 0.7000000000000001, 0.8, 0.9 Test 2: 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0 Test 3: -1.0, -0.5, 0.0, 0.5
Функция NumPy Linspace для генерации диапазона с плавающей запятой
У NumPy есть другой метод linspace(), позволяющий вам создать указанное количество чисел с плавающей запятой. Он имеет следующий синтаксис:
# Syntax linspace(start, stop, num, endpoint) start => starting point of the range stop => ending point num => Number of values to generate, non-negative, default value is 50. endpoint => Default value is True. If True, includes the stop value else ignores it.
Эта функция имеет больше аргументов, но мы описали те, которые соответствуют нашей цели.
Посмотрите на приведенные ниже примеры.
import numpy as np
print("Print Float Range Using NumPy LinSpace()n")
print(np.linspace(1.0, 5.0, num = 5))
print(np.linspace(0, 10, num = 5, endpoint = False))
Вывод следующий:
Print Float Range Using NumPy LinSpace() [1. 2. 3. 4. 5.] [0. 2. 4. 6. 8.]
Если вы не хотите устанавливать пакет NumPy, попробуйте подход в следующем примере.
Генерация диапазона с плавающей запятой без использования сторонних модулей
Здесь мы предоставили простую программу на Python для генерации диапазона чисел с плавающей запятой. Он принимает как положительное так и отрицательное значение для аргументов.
Этот пример имеет 2 логических деления. Первый определяет функцию float_range(). Другой вызывает его с разными входными значениями и печатает результат.
"""
Desc : This function generates a float range of numbers w/o using any library.
Params :
A (int/float) : First number in the range
L (int/float) : Last number in the range
D (int/float) : Step or the common difference
"""
def float_range(A, L=None, D=None):
#Use float number in range() function
# if L and D argument is null set A=0.0 and D = 1.0
if L == None:
L = A + 0.0
A = 0.0
if D == None:
D = 1.0
while True:
if D > 0 and A >= L:
break
elif D < 0 and A <= L:
break
yield ("%g" % A) # return float number
A = A + D
#end of function float_range()
"""
Desc: This section calls the above function with different test data.
"""
print ("nPrinting float range")
print ("nTest 1: ", end = " ")
for i in float_range(0.1, 5.0, 0.5):
print (i, end=", ")
print ("nTest 2: ", end = " ")
for i in float_range(-5.0, 5.0, 1.5):
print (i, end=", ")
print ("nTest 3: ", end = " ")
for num in float_range(5.5):
print (num, end=", ")
print ("nTest 4: ", end = " ")
for num in float_range(10.1, 20.1):
print (num, end=", ")
Вывод следующий:
Printing float range Test 1: 0.1, 0.6, 1.1, 1.6, 2.1, 2.6, 3.1, 3.6, 4.1, 4.6, Test 2: -5, -3.5, -2, -0.5, 1, 2.5, 4, Test 3: 0, 1, 2, 3, 4, 5, Test 4: 10.1, 11.1, 12.1, 13.1, 14.1, 15.1, 16.1, 17.1, 18.1, 19.1,
Использование значения с плавающей запятой в параметре step
В пользовательской функции диапазона мы можем предоставить значение типа с плавающей запятой в качестве аргумента шага. Это позволит нам генерировать числа в определенном интервале.
Давайте рассмотрим пример, в котором в качестве значения шага указано 3.7.
import numpy as pynum_float print( "Display range using a float value in the stepn", pynum_float.arange(3, 33, 3.7) )
Вывод следующий:
Display range using a float value in the step [ 3. 6.7 10.4 14.1 17.8 21.5 25.2 28.9 32.6]
Создать диапазон с плавающей запятой, используя Itertools
Мы также можем использовать модуль itertools и его функции, такие как islice() и count. Посмотрите на приведенный ниже пример, где мы написали простой метод для создания диапазона.
from itertools import islice, count
def iter_range(start, stop, step):
if step == 0:
raise ValueError("Step could not be NULL")
length = int(abs(stop - start) / step)
return islice(count(start, step), length)
for it in iter_range(0, 10, 1.10):
print ("{0:.1f}".format(it), end = " ")
Вывод следующий:
0.0 1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8
Резюме
Хотелось бы, чтобы вы узнали, как генерировать диапазон чисел с плавающей запятой. Вы можете выбрать любой из методов, описанных выше, и использовать его в своих задачах.