The sum of numbers in a line from a file
Chris “Kwpolska” Warrick
kwpolska at gmail.com
Thu Feb 20 19:56:47 CET 2014
On Thu, Feb 20, 2014 at 7:16 PM, <kjakupak at gmail.com> wrote:
> What I've got is
> def stu_scores():
> lines = 
> with open("file.txt") as f:
> return ("".join(lines[11:]))
This returns a string, not a list. Moreover, lines.extend() is
useless. Replace this with:
with open("file.txt") as f:
lines = f.readlines()
> scores = stu_scores()
> for line in scores:
`for` operating on strings iterates over each character.
> fields = line.split()
Splitting one character will turn it into a list containing itself, or
nothing if it was whitespace.
> name = fields
This is not what you want it to be — it’s only a single letter.
> sum1 = int(fields) + int(fields) + int(fields)
Thus it fails here, because ['n'] has just one item, and not nine.
> sum2 = int(fields) + int(fields)
> average1 = sum1 / 3.0
> average2 = sum2 / 2.0
> print ("%s %f %f %") (name, average1, average2)
> It says that the list index is out of range on the sum1 line. I need stu_scores because the table from above starts on line 11.
Chris “Kwpolska” Warrick <http://kwpolska.tk>
stop html mail | always bottom-post | only UTF-8 makes sense
More information about the Python-list