Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument
Okay, so I am trying to learn Python. I had a friend who had an intro to Python class a few semesters ago and he gave me all of his old assignments. I am having a particularly annoying problem that I think should be quite simple, but can't seem to figure out where my problem lies. See what you folks think.
The program is supposed to read from a file called grades.txt. Here is the file:
2
John Doe
82
100
57
0
Jane Smith
91
12
45
81
0
The format of this file is: The first line is the number of students. Then there are the names of the students followed by their grades. The zero symbolizes the end of the student's list of grades. I know, I know...doesn't make a lot of sense to do it that way, but that is the way this reads.
Anyways, here is the code that I have written for it so far....
#!/usr/bin/env python
class students():
def __init__(self, fname='', lname='', grades=[]):
self.firstName = fname
self.lastName = lname
self.gradeBook = grades
def lineCheck(lineText):
try:
int(lineText)
return True
except ValueError:
return False
inFile = "grades.txt"
outFile = "summary.txt"
count = 0
numStudents = 0
studentList = []
check = False
with open(inFile, "r") as file:
for line in file:
if(count == 0):
numStudents = line.strip()
else:
lineRead = line.strip()
check = lineCheck(lineRead)
if(check == False):
studentName = lineRead.split()
fName = studentName[0]
lName = studentName[1]
temp = students(fName, lName)
else:
if(lineRead != '0'):
temp.gradeBook.append(lineRead)
elif(lineRead == '0'):
studentList.append(temp)
count += 1
file.close()
for student in studentList:
print student.firstName + " " + student.lastName
print student.gradeBook
With this code, the expected output for me is at the end of the program in the final for loop. I expect to see something like this:
John Doe
['82', '100', '57']
Jane Smith
['91', '12', '45', '81']
However, the output I am getting is this:
John Doe
['82', '100', '57', '91', '12', '45', '81']
Jane Smith
['82', '100', '57', '91', '12', '45', '81']
I have been staring at this for way too long, and I have a feeling this is something very simple. But as I am new to python and have not gotten fully accustomed to all of its nuances yet, maybe someone with more experienced eyes can pick out what is going on here. I would really appreciate any help you can give me. Thanks.