【问题标题】:I do not get how to get displayGPA() cleanly handle a ZeroDivisionError我不明白如何让 displayGPA() 干净地处理 ZeroDivisionError
【发布时间】:2018-12-16 03:16:47
【问题描述】:
#!/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())

如果没有将课程添加到字典或添加到字典的成绩为 0.0 浮动,则 displayGPA() 可能会被零除 (ZeroDivisionError)。

【问题讨论】:

    标签: python python-3.x scripting


    【解决方案1】:

    您始终可以使用 tryexcept 块。以下是它们如何工作的示例:

    try:
        x = num1 / num2 # num1 and num2 are numbers defined somewhere else in this code
    except ZeroDivisionError:
        print("Zero division error") # Or make Python do something else
    

    【讨论】:

      【解决方案2】:

      你可以试试decimal模块:

      from decimal import *
      
      setcontext(ExtendedContext)
      
      value = 123 / Decimal(0)    # value is now Decimal('Infinity')
      print(str(float(value)))
      

      输出:

      'inf'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-14
        • 2021-10-22
        • 2020-12-13
        • 1970-01-01
        • 1970-01-01
        • 2011-07-22
        相关资源
        最近更新 更多