我使用的是Python 3.4.1,我正在尝试编写执行以下操作的代码:
class Student(object):
def __init__(self, name):
self.name, self.grades = name, []
def append_grade(self, grade):
self.grades.append(grade)
def average(self):
return sum(self.grades) / len(self.grades)
def letter_grade(self):
average = self.average()
for value, grade in (90, "A"), (80, "B"), (70, "C"), (60, "D"):
if average >= value:
return grade
else:
return "F"
def main():
print()
a_class = [] # "class" by itself is a reserved word in Python, avoid using
while True:
print()
print('{} students in class so far'.format(len(a_class)))
another_student = input('Do you have another student to enter (y/n) ? ')
if another_student[0].lower() != 'y':
break
print()
student_name = input('What is the student\'s ID? ')
a_class.append(Student(student_name))
print()
print('student :', student_name)
print('------------------------------------------------')
number_of_tests = int(input('Please enter the number of tests : '))
for test_num in range(1, number_of_tests+1):
print('test grade {}'.format(test_num), end='')
score = float(input(' : '))
if score < 0: # stop early?
break
number_of_assignments = int(input('Please enter the number of assignments : '))
for assignment_num in range(1, number_of_assignments+1):
print('assignment grade {}'.format(assignment_num), end='')
score2 = float(input(' : '))
if score2 < 0: # stop early?
break
number_of_participation = int(input('Please enter 1 to add participation grade : '))
for participation_num in range(1, number_of_participation+1):
print('participation grade {}'.format(participation_num), end='')
score3 = float(input(' : '))
if score3 < 0: # stop early?
break
a_class[-1].append_grade(score + score2 + score3) # append to last student added
print_report(a_class)
def print_report(a_class):
print()
print('Student Grades')
print()
for student in sorted(a_class, key=lambda s: s.name):
print('student: {:20s} average test score: {:3.2f} grade: {}'.format(
student.name, student.average(), student.letter_grade()))
print()
print('The class average is {:.2f}'.format(class_average(a_class)))
def class_average(a_class):
return sum(student.average() for student in a_class) / len(a_class)
main()
这里的任务是通过添加3个不同的东西并获得平均值来获得学生的字母等级。我需要能够输入考试成绩,作业分数和1个参与等级。那些需要平均并给我一个最终的字母等级。我能够找到如何只做一组平均分数但是当我加上其他分数时,平均值是错误的。我可以在这里编辑什么?
答案 0 :(得分:0)
我没有详细看,但是这个:
a_class[-1].append_grade(score + score2 + score3)
...让我怀疑你是在一个等级列表中添加一个值,即高于100%。这可能会导致您的平均值过高。
相反,您应该:
a_class[-1].append_grade(score)
a_class[-1].append_grade(score2)
a_class[-1].append_grade(score3)