- Python TypeError: ‘float’ object cannot be interpreted as an integer Solution
- TypeError: ‘float’ object cannot be interpreted as an integer
- An Example Scenario
- The Solution
- Conclusion
- Питон typeerror float object cannot be interpreted as an integer
- # Table of Contents
- # TypeError: float object cannot be interpreted as an integer
- # Use the floor division operator to solve the error
- # Convert the float to an integer when calling the function
- # Convert the float to an integer by rounding
- # Using numpy.arange to solve the error
- # Reassigning a variable by mistake
- # TypeError: ‘str’ object cannot be interpreted as an integer
- # Convert the string to an integer in the call to the function
- # The input() function always returns a string
- # Reassigning a variable to a string by mistake
Python TypeError: ‘float’ object cannot be interpreted as an integer Solution
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.
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:
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 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.
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!
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.
Питон typeerror float object cannot be interpreted as an integer
Last updated: Feb 1, 2023
Reading time · 5 min
# Table of Contents
# TypeError: float object cannot be interpreted as an integer
The Python «TypeError: ‘float’ object cannot be interpreted as an integer» occurs when we pass a float to a function that expects an integer argument.
To solve the error, use the floor division operator, e.g. for i in range(my_num // 5): .
Here is an example of how the error occurs.
Copied!my_num = 50 print(my_num / 5) # 👉️ 10.0 (float) # ⛔️ TypeError: 'float' object cannot be interpreted as an integer for i in range(my_num / 5): print(i)
The division operator / always produces a float value but the range() function expects an integer.
Floating point numbers have one or more digits after the decimal, whereas integers don’t have a decimal.
Copied!print(type(10.0)) # 👉️ print(type(10.5)) # 👉️ print(type(5)) # 👉️ print(type(13)) # 👉️
# Use the floor division operator to solve the error
To solve the error, use the floor division operator // instead of the division / operator.
Copied!my_num = 50 # ✅ using floor division for i in range(my_num // 5): print(i) print(my_num / 5) # 👉️ 10.0 (float) print(my_num // 5) # 👉️ 10 (int) # ✅ or convert to int print(int(10.0)) # 👉️ 10 (int)
Division / of integers yields a float, while floor division // of integers results in an integer.
The result of using the floor division operator is that of a mathematical division with the floor() function applied to the result.
# Convert the float to an integer when calling the function
Alternatively, you can convert the float to an int by passing it to the int() constructor.
Copied!my_num = 50 # ✅ convert float to int for i in range(int(my_num / 5)): print(i) print(int(10.0)) # 👉️ 10 print(int(5.0)) # 👉️ 5
The int class returns an integer object constructed from the provided number or string argument.
The constructor returns 0 if no arguments are given.
The range function is commonly used for looping a specific number of times in for loops and takes the following parameters:
Name | Description |
---|---|
start | An integer representing the start of the range (defaults to 0 ) |
stop | Go up to, but not including the provided integer |
step | Range will consist of every N numbers from start to stop (defaults to 1 ) |
Copied!print(list(range(5))) # 👉️ [0, 1, 2, 3, 4] print(list(range(1, 5))) # 👉️ [1, 2, 3, 4]
If you only pass a single argument to the range() constructor, it is considered to be the value for the stop parameter.
# Convert the float to an integer by rounding
You can also convert the float to an integer by rounding.
Copied!my_float = 3.51 for i in range(round(my_float)): print(i) # 0, 1, 2, 3 print(round(my_float)) # 👉️ 4
The round function takes the following 2 parameters:
Name | Description |
---|---|
number | the number to round to ndigits precision after the decimal |
ndigits | the number of digits after the decimal, the number should have after the operation (optional) |
The round function returns the number rounded to ndigits precision after the decimal point.
If ndigits is omitted, the function returns the nearest integer.
You can use the math.ceil() or math.floor() method if you need to round the float up or down.
Copied!import math my_float = 3.51 rounded_up = math.ceil(my_float) print(rounded_up) # 👉️ 4 rounded_down = math.floor(my_float) print(rounded_down) # 👉️ 3
The math.ceil method returns the smallest integer greater than or equal to the provided number.
The math.floor method returns the largest integer less than or equal to the provided number.
If you are getting the error in a different scenario, you have to convert the float argument to an integer by passing it to the int() constructor.
# Using numpy.arange to solve the error
The native range() function cannot be called with a floating-point number, but you can call the numpy.arange method with one.
Copied!import numpy as np my_float = 3.5 for i in np.arange(my_float): # 0.0 # 1.0 # 2.0 # 3.0 print(i)
The numpy.arange method takes the start , stop and step values as parameters, just like the range() function.
However, numpy.arange handles floating-point values.
If you need to install numpy, open your terminal in your project’s root directory and run the following command.
Copied!pip install numpy pip3 install numpy
# Reassigning a variable by mistake
Make sure you aren’t declaring a variable that stores an integer initially and overriding it somewhere in your code.
Copied!my_int = 50 # 👇️ reassigned variable to a float by mistake my_int = 5.6 # ⛔️ TypeError: 'float' object cannot be interpreted as an integer for i in range(my_int): print(i)
We initially set the my_int variable to an integer but later reassigned it to a float which caused the error.
# TypeError: ‘str’ object cannot be interpreted as an integer
The Python «TypeError: ‘str’ object cannot be interpreted as an integer» occurs when we pass a string to a function that expects an integer argument.
To solve the error, convert the string to an integer in the call to the function.
Here is an example of how the error occurs.
Copied!# 👇️ this is a string my_num = '5' # ⛔️ TypeError: 'str' object cannot be interpreted as an integer for i in range(my_num): print(i)
We passed a string to the range() constructor which expects an integer argument.
# Convert the string to an integer in the call to the function
To solve the error, use the int() class to convert the string to an integer.
Copied!my_num = '5' for i in range(int(my_num)): print(i)
The int() class returns an integer object constructed from the provided number or string argument.
Copied!print(int('5')) # 👉️ 5 (integer) print(int('3')) # 👉️ 3 (integer)
# The input() function always returns a string
The error often occurs when taking input from the user with the built-in input() function.
Copied!# 👇️ this is a string num = input('Enter your fav number: ') print(num) print(type(num)) # 👉️ # ⛔️ TypeError: 'str' object cannot be interpreted as an integer for i in range(num): print(i)
The input function converts the supplied value to a string and returns it.
The input() function is guaranteed to return a string even if the user enters an integer.
Use the int() constructor to convert the value to an integer to solve the error.
Copied!num = input('Enter your fav number: ') print(num) print(type(num)) # 👉️ # ✅ Convert str to integer for i in range(int(num)): print(i)
The int() class returns an integer object constructed from the provided number or string argument.
The constructor returns 0 if no arguments are given.
Copied!print(int('10')) # 👉️ 10 print(int('5')) # 👉️ 5
The range constructor is commonly used for looping a specific number of times in for loops and takes the following parameters:
Name | Description |
---|---|
start | An integer representing the start of the range (defaults to 0 ) |
stop | Go up to, but not including the provided integer |
step | Range will consist of every N numbers from start to stop (defaults to 1 ) |
Copied!print(list(range(3))) # 👉️ [0, 1, 2] print(list(range(1, 4))) # 👉️ [1, 2, 3]
If you only pass a single argument to the range() constructor, it is considered to be the value for the stop parameter.
# Reassigning a variable to a string by mistake
Make sure you aren’t declaring a variable that stores an integer initially and overriding it somewhere in your code.
Copied!my_int = 10 # 👇️ reassigned variable to a string by mistake my_int = '30' # ⛔️ TypeError: 'str' object cannot be interpreted as an integer for i in range(my_int): print(i)
We initially set the my_int variable to an integer but later reassigned it to a string.
In this case, you have to track down where the variable got set to a string and correct the assignment.
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.