我使用类创建了这个python脚本,它获取了学生姓名,学号,学生课程和成绩。
setTimeout(this._validateInput.bind(this), 2000);
执行后,它成功显示此输出:
#!/usr/bin/env python3
class Student:
def __init__(self, name, number):
self.name = name
self.number = number
self.courses = {}
def displayStudent(self):
return 'Student Name: ' + self.name + '\n' + 'Student Number: ' + str(self.number)
def addGrade(self, course, grade):
self.courses[course] = grade
def displayGPA(self):
gpa = 0.0
try:
if self.courses.keys() != 0.0:
for course in self.courses.keys():
gpa = gpa + self.courses[course]
return 'GPA of student ' + self.name + ' is ' + str(gpa / len(self.courses))
except ZeroDivisionError:
print('oops')
def displayCourses(self):
return [k for k in self.courses.keys() if self.courses[k] > 0]
if __name__ == '__main__':
# Create first student object and add grades for each class
student1 = Student('John', '013454900')
student1.addGrade('uli101', 1.0)
student1.addGrade('ops235', 2.0)
student1.addGrade('ops435', 3.0)
# Create second student object and add grades for each class
student2 = Student('Jessica', '123456')
student2.addGrade('ipc144', 4.0)
student2.addGrade('cpp244', 3.5)
student2.addGrade('cpp344', 0.0)
# Display information for student1 object
print(student1.displayStudent())
print(student1.displayGPA())
print(student1.displayCourses())
# Display information for student2 object
print(student2.displayStudent())
print(student2.displayGPA())
print(student2.displayCourses())
我想要做的是,如果在Student Name: John
Student Number: 013454900
GPA of student John is 2.0
['ops435', 'ops235', 'uli101']
Student Name: Jessica
Student Number: 123456
GPA of student Jessica is 2.5
['ipc144', 'cpp244']
函数下没有添加任何课程,它应该显示ZeroDivisionError。
任何帮助将不胜感激。谢谢:))
答案 0 :(得分:3)
你可以抛出任何错误:
raise ErrorYouWantHere("Some Message")
在你的情况下
raise ZeroDivisionError("No course added")
但问题是,为什么你想要一个ZeroDivisionError
。最好遵循错误的意图,当你尝试将某些东西除零时,ZeroDivisionError
意味着抛出。
也许你想要一个ValueError
?