Dear babutche,
The makestudent() and main() methods in your sample code are
irrelevant to the calculation of cumulative GPA, so I have omitted
them from my own code. I have included many comments in the code to
help you understand how the user feedback loop works.
I ran the program from a UNIX command line to obtain the following test transcript.
$ python student.py
Enter grade for next course, or nothing to finish: 3.0
Enter number of credit hours for this course: 10
Enter grade for next course, or nothing to finish: 4.0
Enter number of credit hours for this course: 30
Enter grade for next course, or nothing to finish: 3.7
Enter number of credit hours for this course: 20
Enter grade for next course, or nothing to finish: 3.3
Enter number of credit hours for this course: 20
Enter grade for next course, or nothing to finish:
*** final GPA = 3.625
The code listing is below.
Regards,
leapinglizard
#===begin student.py
class Student:
def __init__(self, name, hours, qpoints):
self.name = name
self.hours = float(hours)
self.qpoints = float(qpoints)
def getName(self):
return self.name
def getHours(self):
return self.hours
def getQpoints(self):
return self.qpoints
def gpa(self):
return self.qpoints/self.hours
# new mutator method as per specification
def addGrade(self, gradePoint, credits):
self.hours += credits
self.qpoints += credits*gradePoint
if __name__ == '__main__':
# output messages
prompt_grade = 'Enter grade for next course, or nothing to finish: '
prompt_credits = 'Enter number of credit hours for this course: '
error_float = 'error: expected a floating-point number'
# make a new Student object
stu = Student('stu', 0.0, 0.0)
# user-feedback loop
while 1:
# prompt user to enter a grade
grade_str = raw_input(prompt_grade)
# quit if no grade is entered
if grade_str.strip() == '':
break
try:
# convert input to a floating-point value
grade = float(grade_str)
except ValueError:
# if input cannot be converted, restart feedback loop
print error_float
continue
# prompt user to enter the number of credits
credits_str = raw_input(prompt_credits).strip()
try:
# convert input to a floating-point value
credits = float(credits_str)
except ValueError:
# if input cannot be converted, restart feedback loop
print error_float
continue
# update the student's grades
stu.addGrade(grade, credits)
# after user has entered all grades, compute the cumulative GPA
if stu.getHours() == 0.0:
# can't compute GPA if hours = 0
print '*** zero credit hours recorded'
else:
# otherwise, output cumulative GPA and finish
print '*** final GPA =', stu.gpa()
#===end student.py |