Rupang Mehta
Rupang Mehta

Reputation: 1

TypeError: 'float' object is not

I am new to python, I am reading a file and want to extract multiple different values for "X-DSPAM-Confidence: 0.7002" I want to add all the different confidence values.

xfile = open('/Users/Documents/python/mbox-short.txt')
for line in xfile:
    if not line.startswith("X-DSPAM-Confidence:"):
        continue
    xf = (line.rstrip())
    ## Start Counting Lines
    count = 0 
    for numlines in xf:
        count = count + 1
    ## total count of lines with value <<<< code works up to this point
    values = float(line[20:])
    print(values)
    for n in values:
        print(n) 

I get error mentioned below

Traceback (most recent call last):
  File "/Users//Documents/python/chapter7.py", line 14, in <module>
    for n in values:
TypeError: 'float' object is not iterable

Upvotes: 0

Views: 193

Answers (2)

vaylon fernandes
vaylon fernandes

Reputation: 31

A for loop requires a sequence to iter over, eg: A string, a list, tuple, etc. A Float is not a sequence it's a value, basically a number. You can't iter over a value.
I guess what you are trying to do is convert all elements in line[20:] to float and print them one by one.
One solution would be to Iter over the string and then convert the values to float then print them.

values = line[20:]
print(values)
for n in values:
    float_value = float(n)
    print(float_value) 

This will only work you can convert the said values to float i.e. they are either numbers or in this case numeric strings e.g. '1', '2', "Infinity", '1E6', etc. See more on float data type here

Edit: Read in your comment which came after I was done writing that you want to print the value like 0.75560.... In this case, you don't need the loop at all. Just typecast the value and print it

values = float(line[20:])
print(value)

In the method, I wrote about earlier, the for loop takes each value one by one, so if your string is something like '123' and if you do

for n in '123':
    print(n)

Your output would be somthing like:

>> '1'
>> '2'
>> '3'

Upvotes: 0

marckesin
marckesin

Reputation: 71

You can't iterate over a number(float, int, complex). First you need to transform the number to string.

Upvotes: 0

Related Questions