1

I wrote the code below to complete the assignment:

fname = raw_input("Enter file name: ")
fh = open(fname)
total = 0
count = 0 
for line in fh:
    if not line.startswith("X-DSPAM-Confidence:") : continue
    pos = line.find(':')
    num = float(line[pos+1:])
for number in num:
    total = total +num
    count += 1
print 'Average spam confidence:', total/count 

The system keep coming out error message reading that

float object is not iterable

I know that I made a mistake from for number in num: And the correct answer is:

fname = raw_input("Enter file name: ")
fh = open(fname)
total = 0
count = 0 
for line in fh:
    if not line.startswith("X-DSPAM-Confidence:") : continue
    pos = line.find(':')
    num = float(line[pos+1:])
    total = total +num
    count += 1
print 'Average spam confidence:', total/count 

but my question is : in the correct answer, is float object also iterable? Thanks for the help!!

1
  • How should an iteration over 3.14 work? Commented Oct 24, 2016 at 3:08

1 Answer 1

1

As the Python glossary notes, an object is an iterable if it is "capable of returning its members one at a time." num is a float, which is just just one number, and it cannot return it's elements one at a time like a list, a set, or a dictionary. Thus, it makes no sense to write for number in num: - for this to work, num should be a iterable, so that it can return it's members one at a time as number. Instead, you should just add the num to the total directly by calling total = total + num (or even better, total += num)

Sign up to request clarification or add additional context in comments.

1 Comment

Note that you could do for number in range(num) which works for integer arguments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.