python - 我不明白如何让 displayGPA() 干净地处理 ZeroDivisionError
问题描述
#!/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):
if len(self.courses) == 0:
errormsg = print('Wrong Input')
return errormsg
else:
gpa = 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))
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())
如果没有课程添加到字典或添加到字典的成绩是浮点数,则问题displayGPA()
可能会除以零 ( )。ZeroDivisionError
0.0
解决方案
您可以尝试decimal
模块:
from decimal import *
setcontext(ExtendedContext)
value = 123 / Decimal(0) # value is now Decimal('Infinity')
print(str(float(value)))
输出:
'inf'
推荐阅读
- javascript - 如何自定义使用 createObjectURL 创建的 URL,
- powershell - 在 Powershell 中过滤具有多个条件的 Foreach-Object 结果不起作用
- php - 显示角色名称 (ID) 和显示角色名称
- nginx - iframe 为我的 Domino XPages 解决方案提供问题(使用 Nginx 代理)添加 JS 代码以使用 http 重定向(而站点是 https)
- c++ - c++中的长长输出
- xamarin.forms - 在 Xamarin Essentials 中保存对象列表
- python - 类“Runattr”的未解析属性引用“cfg”
- android - android volley 基本请求不适用于特殊网站
- angular - 预渲染角度应用程序时无法从应用程序中提取路由
- android - Firebase 实时数据库规则不适用于新用户