[Tutor] Reading Data From File

Dave Angel davea at dejaviewphoto.com
Sat Jul 25 23:37:55 CEST 2009


ctcast at gmail.com wrote:
> grades = []
> names = []
> gradeTotal = 0
> numStudents = 0
>
> inputFile = open("input.txt", "r"
>
> for line in inputFile:
> if line.strip().isdigit():
> grade = float(line)
> if grade != 0.0:
> gradeTotal += grade
> grade = grades.append(grade)
> else:
> name = line.strip()
> name = names.append(name)
>
> This just loops over the entire file basically and just continually 
> adds the grades to the grades list and names to the names list. How do 
> I just process each student's set of grades before moving on to the 
> next one (since there is a zero terminating value telling the loop 
> that a new student and his or her grades are about to follow)
>
> By the way I'm not worrying about determining the letter grade average 
> right now, i'm importing a module I wrote after I figure this part out.
>
> On Jul 25, 2009 8:34am, bob gailer <bgailer at gmail.com> wrote:
>> I concur with wesley and dave re homework.
> <snip>
>
There are syntax errors of at least two kinds here.  The first is you're 
missing a trailing parenthesis.  And the second is you lost all your 
indentation when you retyped the code.  It'd really be better if you 
pasted the actual code instead.  Not much of a problem in this case, at 
least if I guess the same as you had, but in many cases the indentation 
*is* the problem.

Next problem is that you're assuming that list.append() returns 
something useful. It doesn't return anything, which is to say it returns 
"None."  So it's not useful to do:
     grade = grades.append(grade)

just leave off the left half of that.  And likewise leave off the name=  
from the other call to append().

The next problem is that you have two independent lists, but no way to 
correlate which elements of one correspond to which elements of the 
other. So you have a choice to make.  Do you need all the data for 
post-processing, or is it enough that you print it out, and discard it 
afterwards?

I'll assume that you'd answer that it's enough to just be able to print 
it out.  In that case, you just need some well placed print statements.  
Each time you come to a line with a zero in it, you have enough 
information to print out one student's information.  And in this case, 
you don't need a list of students, just the name of the current one.

Do you expect any numbers to be non-integers?  I'd assume so because you 
used the float() function instead of int().  But isdigit() is going to 
be a problem if there's a decimal in there.

DaveA



More information about the Tutor mailing list