Typeerror float object is not iterable что за ошибка
Перейти к содержимому

Typeerror float object is not iterable что за ошибка

TypeError: 'float' object not iterable

I’m using python 3.2.2 on windows 7 and I’m trying to create a program which accepts 7 numbers and then tells the user how many are positive, how many are negative and how many are zero. this is what I have got so far:

But when I run the code I get

If I replace float in line 3 with int I get the same problem except it says that the ‘int’ object is not iterable. I have also tried changing the value of count from 7 to 7.0

Now I took this challenge from a python tutorial book and they don’t have the answer, and from what I can tell I have done everything within the syntax they put forward.

Python TypeError: ‘float’ object not iterable Solution

James Gallagher

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.

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:

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:

81% of participants stated they felt more confident about their tech job prospects after attending a bootcamp. Get matched to a bootcamp today.

Find Your Bootcamp Match

The average bootcamp grad spent less than six months in career transition, from starting a bootcamp to finding their first job.

Start your career switch today

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:

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:

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

How to Solve TypeError: ‘float’ object is not iterable

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?

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.

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.

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

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.

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.

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

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.

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.

Let’s run the code to see what happens:

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:

Let’s run the code to see what happens:

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!

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *