Float object cannot be interpreted as an integer как исправить

Know the Python "TypeError: 'float' object cannot be interpreted as an integer" solution in this article, which occurs when you pass float values to range(). Read More »

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

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.

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.

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

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.

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!

0 / 0 / 0

Регистрация: 06.03.2019

Сообщений: 35

1

22.04.2019, 22:28. Показов 10030. Ответов 4


Как исправить ошибку ‘float’ object cannot be interpreted as an integer
нажимаю место этой ошибки открывается строка в другом коде где написано a = empty(shape, dtype, order)

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import numpy as np
import pylab as pl
import scipy.signal.signaltools as sigtool
import scipy.signal as signal
from numpy.random import sample
 
#the following variables setup the system
Fc = 1000       #simulate a carrier frequency of 1kHz
Fbit = 50       #simulated bitrate of data
Fdev = 500      #frequency deviation, make higher than bitrate
N = 64          #how many bits to send
A = 1           #transmitted signal amplitude
Fs = 10000      #sampling frequency for the simulator, must be higher than twice the carrier frequency
A_n = 0.10      #noise peak amplitude
N_prntbits = 10 #number of bits to print in plots
 
def plot_data(y):
    #view the data in time and frequency domain
    #calculate the frequency domain for viewing purposes
    N_FFT = float(len(y))
    f = np.arange(0,Fs/2,Fs/N_FFT)
    w = np.hanning(len(y))
    y_f = np.fft.fft(np.multiply(y,w))
    y_f = 10*np.log10(np.abs(y_f[0:N_FFT/2]/N_FFT))
    pl.subplot(3,1,1)
    pl.plot(t[0:Fs*N_prntbits/Fbit],m[0:Fs*N_prntbits/Fbit])
    pl.xlabel('Time (s)')
    pl.ylabel('Frequency (Hz)')
    pl.title('Original VCO output versus time')
    pl.grid(True)
    pl.subplot(3,1,2)
    pl.plot(t[0:Fs*N_prntbits/Fbit],y[0:Fs*N_prntbits/Fbit])
    pl.xlabel('Time (s)')
    pl.ylabel('Amplitude (V)')
    pl.title('Amplitude of carrier versus time')
    pl.grid(True)
    pl.subplot(3,1,3)
    pl.plot(f[0:(Fc+Fdev*2)*N_FFT/Fs],y_f[0:(Fc+Fdev*2)*N_FFT/Fs])
    pl.xlabel('Frequency (Hz)')
    pl.ylabel('Amplitude (dB)')
    pl.title('Spectrum')
    pl.grid(True)
    pl.tight_layout()
    pl.show()
    
"""
Data in
"""
#generate some random data for testing
data_in = np.random.random_integers(0,1,N)
 
"""
VCO
"""
t = np.arange(0,float(N)/float(Fbit),1/float(Fs), dtype=np.float)
#extend the data_in to account for the bitrate and convert 0/1 to frequency
m = np.zeros(0).astype(float)
for bit in data_in:
    if bit == 0:
        m=np.hstack((m,np.multiply(np.ones(Fs/Fbit),Fc+Fdev)))
    else:
        m=np.hstack((m,np.multiply(np.ones(Fs/Fbit),Fc-Fdev)))
#calculate the output of the VCO
y=np.zeros(0)
y=A * np.cos(2*np.pi*np.multiply(m,t))
plot_data(y)

Миниатюры

Ошибка 'float' object cannot be interpreted as an integer
 

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Понравилась статья? Поделить с друзьями:
  • Flibusta network error что делать
  • Flexray bmw ошибка
  • Flexnet licensing finder autocad как исправить
  • Flexnet licensing error 97 121
  • Flexnet licensing error 96 491