Ok, so I’m new to python and I’m currently taking the python for everybody course (py4e).
Our lesson 7.2 assignment is to do the following:
7.2 Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:
X-DSPAM-Confidence: 0.8475Count these lines and extract the floating point values from each of the lines and compute the average of those values and produce an output as shown below. Do not use the sum() function or a variable named sum in your solution. You can download the sample data at http://www.py4e.com/code3/mbox-short.txt when you are testing below enter mbox-short.txt as the file name.
I can’t figure it out. I keep getting this error
ValueError: float: Argument: . is not number on line 12
when I run this code (see screenshot): https://gyazo.com/a61768894299970692155c819509db54
Line 12 which is num = float(balue) + float(num)
keeps acting up. When I remove the float from balue then I get another which says
“TypeError: cannot concatenate ‘str’ and ‘float’ objects on line 12”.
Can arguments be converted into floats or is it only a string? That might be the problem but I don’t know if it’s true and even if it is I don’t know how to fix my code after that.
Advertisement
Answer
Your approach was not so bad I would say. However, I do not get what you intended with for balue in linez
, as this is iterating over the characters contained in linez. What you rather would have wanted float(linez). I came up with a close solution looking like this:
fname = raw_input("Enter file name: ") print(fname) count = 0 num = 0 with open(fname, "r") as ins: for line in ins: line = line.rstrip() if line.startswith("X-DSPAM-Confidence:"): num += float(line[20:]) count += 1 print(num/count)
This is only intended to get you on the right track and I have NOT verified the answer or the correctness of the script, as this should be contained your homework.