Float object is not iterable python ошибка

Floats and iterables are distinct objects In Python. A float is any decimal point number, and an iterable is an object capable of returning elements one

Floats and iterables are distinct objects In Python. A float is any decimal point number, and an iterable is an object capable of returning elements one at a time, for example, a list. A float is a single value and does not contain other values. If you try to iterate over a float, you will raise the error “TypeError: ‘float’ object is not iterable“.

To solve this error, ensure you use the range() method, for example,

for number in range(floating_point_number)

to iterate over a range of numbers up to the specified floating_point_number.

This tutorial will go through the error in detail. We will go through two example scenarios and learn how to solve them.


Table of contents

  • TypeError: ‘float’ object not iterable
    • What is a TypeError?
    • Difference Between a Float and an Iterable
  • Example #1: Iterate Over a Floating Point Number
    • Solution #1: Convert float to string Using the str() Method
    • Solution #2: Iterate Using the range() Method
  • Example #2: Determine if a Number is Prime
    • Solution
  • Summary

TypeError: ‘float’ object not iterable

What is a TypeError?

A TypeError occurs when we try to perform an operation on the wrong type of object. For example, if we try to calculate the square root of a list instead of an integer or a floating-point number, then a TypeError will be generated by the Python interpreter.

Difference Between a Float and an Iterable

Iterables are containers that can store multiple values and return them one by one. Iterables can store any number of values, and the values can either be the same type or different types. You can go to the next item in an iterable object using the next() method.

A floating-point number is any number with a decimal point. You can define a floating-point number in Python by defining a variable and assigning a decimal point number to it.

x = 4.2

print(type(x))
class 'float'

Floating-point numbers do not store multiple values like a list or a dictionary. If you try to iterate over a float, you will raise the error “TypeError: ‘float’ object is not iterable” because float does not support iteration.

You will get a similar error if you try to iterate over an integer or a NoneType object.

Example #1: Iterate Over a Floating Point Number

Let’s look at an example where we initialize a floating-point number and iterate over it.

# Define floating point number

float_num = 10.0 

# Iterate over the floating point number

for num in float_num:

    print(num)

Let’s see what happens when we run the code:

TypeError                                 Traceback (most recent call last)
      1 for num in float_num:
      2     print(num)
      3 

TypeError: 'float' object is not iterable

We raise the error because Python does not support iteration on a floating-point number.

Solution #1: Convert float to string Using the str() Method

The first solution involves converting the float_num object to a string using the str() method and iterating over every digit. We can do iteration over a string because the string type is iterable. However, the for loop will return each character of the float_num string.

# Define floating point number

float_num = 10.0 

# Iterate over the floating point number

for digit in str(float_num):

    print(digit)

Solution #2: Iterate Using the range() Method

To print the range of numbers, we can use the int() method to convert the number to an integer and then use the integer as input to the range() method. The range() method only accepts integer numbers, in which case we have to convert any floating-point number that we want to iterate over to an integer. The range() method returns an iterable object which we can iterate over using a for loop.

# Define floating point number

float_num = 30.0 

# Convert the float number to an integer

int_num = int(float_num)

# Iterate over the floating point number

for num in range(int_num):

    print(num)

Let’s see what happens when we run the revised code:

0
1
2
3
4
5
6
7
8
9

Example #2: Determine if a Number is Prime

Let’s look at another example where we write a program to check if a number entered by the user is prime or not. Prime numbers are only divisible by themselves, and 1. To start, we will ask the user to insert the number to determine whether it is prime or not.

number = float(input("Enter a number:  "))

Then we define a function that determines whether the number is prime by using the modulo operator %. If the remained of x % y equals zero, then y is a factor of x. Prime numbers have two factors, one and itself.

# Function to determine if number is prime or not

def prime_number_calc(num):

    for i in num:
        # Ensure we do not divide the number by zero or one

        if i > 1:

            if num % i == 0:

                 print(f'{num} is not prime')

                 break

    # If the loop runs completely the number is prime

    else:

        print(f'{num} is a prime number')
prime_number_calc(number)

Let’s run the code to see what happens:

TypeError                                 Traceback (most recent call last)
      1 def prime_number_calc(num):
      2     for i in num:
      3         if i > 1:
      4             if num % i == 0:
      5                 print(f'{num} is not prime')

TypeError: 'float' object is not iterable

The Python interpreter throws the TypeError because a floating-point number is not a suitable type to iterate over. A for loop requires an iterable object to loop over.

Solution

To solve this problem, we need to convert the input number to an integer using int() and pass the integer the range() method instead of the float. Let’s look at the revised code:

def prime_number_calc(num):

     for i in range(int(num)):

         if i > 1:

             if num % i == 0:

                 print(f'{num} is not prime')

                 break
     else:

         print(f'{num} is a prime number')
number = float(input("Enter a number:  "))

prime_number_calc(number)

Let’s run the code to see what happens:

Enter a number:  17.0

17.0 is a prime number

Our code successfully prints the result that 17.0 is a prime number.

Summary

Congratulations on reading to the end of this tutorial. The error “TypeError: ‘float’ object is not iterable” occurs when you try to iterate over a floating-point number as if it were an iterable object like a list.

You must use the range() method to iterate over a collection of numbers. However, you must convert the float to an integer beforehand passing it to the range() method. If you want to iterate over the digits of the float, you can convert the float to a string and use the range() function.

To learn more about Python for data science and machine learning, go to the online courses pages on Python for the best courses online!

Have fun and happy researching!

Python can only iterate over an iterable object. This is a type of object that can return its members one at a time. If you try to iterate over a non-iterable object, like a floating-point number, you see an error that says “TypeError: ‘float’ object not iterable”.

In this guide, we talk about what this error means and why you may encounter it. We walk through an example to help you understand how to resolve this error in your code.

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.

TypeError: ‘float’ object not iterable

Iterable objects include list, strings, tuples, and dictionaries. When you run a for loop on these data types, each value in the object is returned one by one.

Numbers, such as integers and floating points, are not iterable. There are no members in an integer or a floating-point that can be returned in a loop.

The result of the “TypeError: ‘float’ object not iterable” error is usually trying to use a number to tell a for loop how many times to execute instead of using a range() statement.

An Example Scenario

Here, we write a program that calculates the factors of a number. To start, we ask the user to insert a number whose factors they want to calculate:

factor = float(input("Enter a number: "))

The input() method returns a string. We cannot perform mathematical operations on a string. We’ve used the float() method to convert the value returned by input() to a floating-point number so that we can use it in a math operation.

Next, we write a for loop that calculates the factors of our number:

for n in factor:
	if factor % n == 0:
		print("{} is a factor of {}.".format(factor, n))

This loop should go through every number until it reaches “factor”.

This loop uses the modulo operator to check whether there is a remainder left after dividing the factor by “n”, which is the number in an iteration of our loop. If there is a remainder, “n” is not a factor. If there is a remainder, our “if” statement executes and prints a message to the console.

Run our code and see what happens:

Enter a number: 8
Traceback (most recent call last):
  File "main.py", line 3, in <module>
	for n in factor:
TypeError: 'float' object is not iterable

Our code returns a TypeError.

The Solution

In our example above, we’ve tried to iterate over “factor”, which is a float. We cannot iterate over a floating-point number in a for loop. Instead, we should iterate over a range of numbers between 1 and the number whose factor we want to calculate.

To fix our code, we need to use a range() statement. The range() statement generates a list of numbers in a specified range upon which a for loop can iterate. Let’s revise our for loop to use a range() statement:

for n in range(1, int(factor) + 1):
	if factor % n == 0:
		print("{} is a factor of {}.".format(factor, n))

Our range() statement generates a list of numbers between one and the value of “factor” plus one.

We have added 1 to the upper end of our range so that our “factor” number is considered a factor. Our for loop can then iterate over this list. We’ve converted “factor” to an integer in our code because the range() statement does not accept floating point numbers.

Run our code again and see what happens:

8.0 is a factor of 1.
8.0 is a factor of 2.
8.0 is a factor of 4.
8.0 is a factor of 8.

Our code successfully returns a list of all the factors of the number we inserted into our program.

Conclusion

The Python “TypeError: ‘float’ object not iterable” error is caused when you try to iterate over a floating point number as if it were an iterable object, like a list or a dictionary.

To solve this error, use a range() statement if you want to iterate over a number. A range statement generates a list of numbers in a given range upon which a for loop can iterate.

Now you’re ready to fix this common Python error in your code!

I’m trying to create a code that will solve for x using the quadratic formula. For the outputs I don’t want it to display the imaginary numbers…only real numbers. I set the value inside the square root to equal the variable called «root» to determine if this value would be pos/neg (if it’s neg, then the solution would be imaginary).

This is the code.

import math

print("Solve for x when ax^2 + bx + c = 0")

a = float(input("Enter a numerical value for a: "))
b = float(input("Enter a numerical value for b: "))
c = float(input("Enter a numerical value for c: "))

root = math.pow(b,2) - 4*a*c

root2 = ((-1*b) - math.sqrt(root)) / (2*a)
root1 = ((-1*b) + math.sqrt(root)) / (2*a)

for y in root1:
    if root>=0:
        print("x =", y)       
    elif root<0:
        print('x is an imaginary number')

for z in root2:
    if root>=0:
        print("or x =", z)
    elif root<0:
        print('x is an imaginary number')

This is the error code:

  File "/Users/e/Documents/Intro Python 2020/Project 1/Project 1 - P2.py", line 25, in <module>
    for y in root1:

TypeError: 'float' object is not iterable

The error occurs at the line:

for y in root1:

How do I fix this error?

asked Apr 10, 2020 at 23:39

emdelalune's user avatar

4

I understand you are using the quadratic equation here. An iterable is something like a list. A variable with more than 1 element. In your example

root1 is a single float value. root2 is also a single float value. For your purposes, you do not need either lines with the «for». Try removing the for y and for z lines and running your code.

To help you understand, a float value is simply a number that has decimals.

answered Apr 10, 2020 at 23:42

Sri's user avatar

SriSri

2,2312 gold badges16 silver badges22 bronze badges

Well, the error is pretty self explanatory: you are trying to loop over root1 and root2 which are floats, not lists.

What I believe you wanted to do instead is simply use if/else blocks:

if root >= 0:
    print("x =", root1)
    print("x =", root2)
else:
    print("x is an imaginary number")

answered Apr 10, 2020 at 23:45

Anis R.'s user avatar

Anis R.Anis R.

6,5282 gold badges13 silver badges37 bronze badges

I’m trying to create a code that will solve for x using the quadratic formula. For the outputs I don’t want it to display the imaginary numbers…only real numbers. I set the value inside the square root to equal the variable called «root» to determine if this value would be pos/neg (if it’s neg, then the solution would be imaginary).

This is the code.

import math

print("Solve for x when ax^2 + bx + c = 0")

a = float(input("Enter a numerical value for a: "))
b = float(input("Enter a numerical value for b: "))
c = float(input("Enter a numerical value for c: "))

root = math.pow(b,2) - 4*a*c

root2 = ((-1*b) - math.sqrt(root)) / (2*a)
root1 = ((-1*b) + math.sqrt(root)) / (2*a)

for y in root1:
    if root>=0:
        print("x =", y)       
    elif root<0:
        print('x is an imaginary number')

for z in root2:
    if root>=0:
        print("or x =", z)
    elif root<0:
        print('x is an imaginary number')

This is the error code:

  File "/Users/e/Documents/Intro Python 2020/Project 1/Project 1 - P2.py", line 25, in <module>
    for y in root1:

TypeError: 'float' object is not iterable

The error occurs at the line:

for y in root1:

How do I fix this error?

asked Apr 10, 2020 at 23:39

emdelalune's user avatar

4

I understand you are using the quadratic equation here. An iterable is something like a list. A variable with more than 1 element. In your example

root1 is a single float value. root2 is also a single float value. For your purposes, you do not need either lines with the «for». Try removing the for y and for z lines and running your code.

To help you understand, a float value is simply a number that has decimals.

answered Apr 10, 2020 at 23:42

Sri's user avatar

SriSri

2,2312 gold badges16 silver badges22 bronze badges

Well, the error is pretty self explanatory: you are trying to loop over root1 and root2 which are floats, not lists.

What I believe you wanted to do instead is simply use if/else blocks:

if root >= 0:
    print("x =", root1)
    print("x =", root2)
else:
    print("x is an imaginary number")

answered Apr 10, 2020 at 23:45

Anis R.'s user avatar

Anis R.Anis R.

6,5282 gold badges13 silver badges37 bronze badges

Float is an non iterable python datatype and typeerror float object is not iterable occurs only when any python statement invokes float as iterable element in loop etc. In this article, we will explore multiple scenarios where we face this error. We will understand the root cause of this error and apply the same to fix different scenarios.

Typeerror float object is not iterable ( Deep Dive in Root Cause ) –

Usually we run the loop over iterable objects. In each iteration , It returns next value for the sequence. Like list, dict, tuple are iterable object. But float is not iterable object. Its single value element. Lets see with code for more clarity-

element= 7.5
for i in element:
  print(i)

Typeerror float object is not iterable

Typeerror float object is not iterable

How to check float is iterable or not ?

If any python object is iterable then its override the method __iter__() in its class and the best way to check the same is using dir() function.

print(dir(float))

Output –

['__abs__', '__add__', '__bool__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getformat__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__int__', '__le__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__pos__', '__pow__', '__radd__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rmod__', '__rmul__', '__round__', '__rpow__', '__rsub__', '__rtruediv__', '__set_format__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', 'as_integer_ratio', 'conjugate', 'fromhex', 'hex', 'imag', 'is_integer', 'real']

Since __iter__() is missing hence float is not iterable object

There are infinite business logic where we face this error. But developer intention and root cause for this error is common everywhere. In this section lets understand the same.

Case 1 : Solution for looping scenario using range –

Usually when we want to loop any logic, we need to define the counter and there if we pass float we get this error. The straight fix for this using range. Basically range converts number to an iterable list. But make sure range only accepts interger values so if we pass float directly into range function we get this error – Typeerror: float object cannot be interpreted as an integer . Hence we will convert the float to int and then pass in range() function. Here is the implementation-

element= 7.5
for i in range(int(element)):
  print(i)

float object is not iterable range()

float object is not iterable range()

Case 2 : Float iteration as str object –

As you know str objects in python are iterable. In some scenarios developer needs to iterate Float object as string only. But they somehow forgot to typecast the float object into str . Hence they get this error.

element= 7.5
for i in str(element):
  print(i)

float object is not iterable fix by str()

float object is not iterable fix by str()

Here interpreter is iterating over the digits of float object as string.

Similar Typeerror on Iterable objects –

Just like Float, int and NoneType objects are not iterables. These error are similar to each others but occurs in different business logics. You can read more about them here-

Typeerror nonetype object is not iterable : Complete Solution

Typeerror int object is not iterable : Root cause and Fix

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 error TypeError: ‘float’ object is not iterable. This error occurs when we try to iterate through a float value which we know is not iterable.

TypeError: 'float' object is not iterable

TypeError: 'float' object is not iterable

Let us understand it more with the help of an example.

Example 1:

for i in 3.4:
 print("this doesn't work")

Output:

File "none3.py", line 1, in <module>
for i in 3.4:
TypeError: 'float' object is not iterable

Explanation:

In the above example, we are trying to iterate through a ‘for loop’ using a float value. But the float is not iterable. Float objects are not iterable because of the absence of the __iter__ method. Which we have discussed about in the below example 2.

Thus the error TypeError: float object is not iterable occurs.  

Example 2:

list = [2,4,8,3]
for x in list:
 print(x)

Output:

2
4
8
3

Explanation:

In the above example, we are trying to print the list elements using the ‘for loop’. since the list is iterable, thus we can use the for loop for iteration.

To know whether an object is iterable or not we can use the dir() method to check for the magic method __iter__. If this magic method is present in the properties of specified objects then that item is said to be iterable

To check, do: dir(list) or dir(3.4)

Code:

List= [ ]
print(dir(list))

Output:

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

__iter__magicmethod is present.

Code:

print(dir(3.4))

Output:

['__abs__', '__add__', '__bool__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getformat__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__int__', '__le__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__pos__', '__pow__', '__radd__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rmod__', '__rmul__', '__round__', '__rpow__', '__rsub__', '__rtruediv__', '__set_format__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', 'as_integer_ratio', 'conjugate', 'fromhex', 'hex', 'imag', 'is_integer', 'real']

__iter__ magic method is absent.

Conclusion

The presence of the magic method __iter__ is what makes an object iterable. From the above article, we can conclude that the __iter__ method is absent in the float object. Whereas it is present in the list object. Thus float is not an iterable object and a list is an iterable object.

To solve TypeRrror: ‘float’ object is not iterable exception in Python, convert the floating-point number into a string. To handle the TypeError, you can also use the try-except statement. The try-except statement built-in exception handler can handle exceptions whenever it is thrown.

The TypeError: ‘float’ object is not iterable raises when we iterate over the floating object. We can iterate through strings, lists, tuples, and dictionaries. Other than these data types, we cannot iterate over them. If we iterate over the floating object, a TypeError exception is thrown.

Example

lst = [1.5, 2.5, 3.5, 4.5, 5.5]

for i in lst:
  print(i, end=" ")

Output

In this example, we defined a list, and then it is iterated over all the elements using the for loop. So the output for this program will be 1.5, 2.5, 3.5, 4.5, and 5.5.

Moving over all the elements in a list is known as the list traversal or iteration. In this example, we have seen how to traverse the floating-point objects list. Now let us see how we can traverse over a string.

str = "Hello"

for i in str:
   print(i + "")

Output

You can see from the output that we can traverse over strings. In string traversal in every iteration, each letter is printed.

Now let’s slightly modify the program and assign a floating-point number to the variable in the same program.

fp = 2.1

for i in fp:
  print(i + "")

Output

TypeError: 'float' object is not iterable

We expect the program to output like 1 . 7 5, but this won’t happen; instead, it throws an error known as the “float” object, which is not iterable.

Floating numbers can not be traversed using for loop in Python. However, we can traverse the numbers to obtain the desired output.

fp = 2.1

try:
  for i in fp:
  print(i, end=" ")
except TypeError:
  print("TypeError has occurred")

Output

Hence to solve this TypeError, we can convert the float number to a string, and then we can iterate over it.

fp = 2.10

temp = str(fp)
for i in temp:
  print(i, end=" ")

Output

The output is like 2 . 1  0. Hence we can convert the floating object into a string and iterate over the string. However, we cannot use a floating-point number in the range.

for i in range(2.1):
  print(i, end=" ")

Output

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

This code throughs a TypeError: ‘float’ object is not iterable. To solve this error, use the int() method.

for i in range(int(5.0)):
   print(i, end=" ")

Output

This code will get executed, and the output will be displayed as 0 1 2 3 4. Hence, we can convert a float number to an integer to use this number in the range() method.

That’s it for this tutorial.

See also

ArithmeticError in Python

TypeError: list indices must be integers or slices, not str

ZeroDivisionError: division by zero

Krunal Lathiya

Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. In addition, Krunal has excellent knowledge of Data Science and Machine Learning, and he is an expert in R Language. Krunal has experience with various programming languages and technologies, including PHP, Python, and JavaScript. He is comfortable working in front-end and back-end development.

In Python, we have some iterable objects such as a string, list, tuple, dictionary, and set. The one property of these iterable objects is we can perform for loop over them and access their individual elements one by one. We can use the for loop and iterate over these iterable objects. There are many other functions, such as map, range, and filter, which also return iterable objects. But if we try to perform an iteration on a floating-point number, we will receive the error

TypeError: 'float' object is not iterable

.

This Python tutorial will discuss this error in detail and see why it occurs and how to debug it. We will also walk through a common example of when many python developers encounter this error. So let’s get started with the Error Statement.

The Error statement

TypeError: 'float' object is not iterable

has two parts Exception Type and Error message.


  1. TypeError (Exception Type)

  2. ‘float’ object is not iterable (Error Message)


1. TypeError



TypeError


is a standard Python error. It is raised when we try to perform an invalid or unsupported operation on a Python object.


2.  ‘float’ object is not iterable

This is the error message telling us that we are performing an iteration operation on a floating-point object, and Python does not support iteration on a floating-point number.


Example

float_num = 30.0        #initialize a float number object

#iterate over a float number(error)
for num in float_num:
    print(num)


Output

Traceback (most recent call last):
  File "main.py", line 4, in 
    for num in float_num:
TypeError: 'float' object is not iterable


Break the code

In this example, we are getting this error because we are trying to loop over the

float_num

variable, which is a floating-point number. And Python for loop can not iterate over a

float

object, so the interpreter threw the error.


Solution

There can be two case scenarios with the above example, we can either want to iterate over the digits of the float number, or we want to create a range of numbers from 0 up to the float number

float_num

. If we want to iterate over every digit of the

float_num

we can convert the object into a string using the str function and iterate over every digit.


Solution 1 (Iterate over every digit)

float_num = 30.0

for digit in str(float_num):
    print(digit)


Output

3
0
.
0

If we want to print the range of numbers from o to

float_num

we first need to convert the float num object to an integer using

int()

function then use that int number into the

range()

function so the for loop can iterate over the iterable object returned by the range() function.

We can not use the float number as an argument value to the range() function, because range function only accepts

int

value.


Solution 2 (Iterate over the range from 0 to

float_num

)

# initialize the float num
float_num = 30.0

# convert the float num into integer
int_num = int(float_num)       #30

for num in range(int_num):
    print(num, end="->")


Output

0->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->


Common Example Scenario

Many Python learners encounter this error when they directly use the float number with the for loop and forget to use the

range()

function. However, the

range()

the function also does not work with floating-point numbers because it only accepts integer numbers as argument values. Still, many new python learners commit the mistake of using the floating-point number with for loop and encounter the  TypeError: ‘float’ object

is not iterable

Error.


Example

Let’s create a Python program that tells if the entered number is a Prime or not.

# ask the user to enter a number
number = float(input("Enter a number: "))

for i in number:
    # check if the number is not a prime
    if number%i==0:
        print(f"{number} is not prime")
        break
# if the for loop run completly
else:
    print(f"{number} is a prime number")


Output

Enter a number: 5
Traceback (most recent call last):
  File "main.py", line 4, in 
    for i in number:
TypeError: 'float' object is not iterable


Break the code

In the above example, we are getting this error because in line 4, we are performing the for loop on the

number

object, which is the number entered by the user and converted into float using the

float()

function.


Solution

To solve the above problem, we need to take care of three things.

  1. First, convert the user input into int before using it in the for a loop.
  2. Second, use the range function instead of the integer or float when dealing with for loop.
  3. Third, we need to start the range function from

    2

    to user entered

    number

    . Because inside the for loop, we are performing modulo operation, and behind the scene, modulo operator use division operation, and when it tries do divide any number with 0, it returns the ZeroDivision Error.


Solution

# ask the user to enter a number and conver it into int
number = int(input("Enter a number: "))

for i in range(number):
    # check if the number is not a prime
    if number%i==0:
        print(f"{number} is not prime")
        break
# if the for loop run completly
else:
    print(f"{number} is a prime number")


Output

Enter a number: 79
79 is a prime number


Wrapping Up!

Now let’s wrap up our article “TypeError: ‘float’ object not iterable” Solution. In this article, we discussed what this error is in Python and how to solve it. This error occurs when we perform the iteration operation or for loop on a Python floating-point number. This is a TypeError exception because

for

loop operation is not supported by floating-point numbers. Mostly this error is raised when the user forgets to put the range function and directly apply the for loop on a floating number.

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


People are also reading:

  • Python indexerror: list index out of range Solution

  • Python TypeError: unhashable type: ‘slice’ Solution

  • Python TypeError: unsupported operand type(s) for -: ‘str’ and ‘int’ Solution

  • Python typeerror: list indices must be integers or slices, not str Solution

  • Python SyntaxError: unexpected EOF while parsing Solution

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

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

  • Python NameError name is not defined Solution

  • Python AttributeError: ‘NoneType’ object has no attribute ‘append’Solution

  • Read File in Python

Понравилась статья? Поделить с друзьями:
  • Float object is not callable ошибка
  • Float object cannot be interpreted as an integer как исправить
  • Flibusta network error что делать
  • Flexray bmw ошибка
  • Flexnet licensing finder autocad как исправить