You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过try-except块实现Python类方法返回成绩等级?

Fixing Your StudentClass Grade Calculation Issues

Hey there! I see you're dipping your toes into Python classes and hit a couple of snags in your StudentClass code. Let's break down the problems and get everything working smoothly.

Identified Issues

Let's start with the two clear bugs you noted, plus a quick tweak to make your exception handling more robust:

  • Wrong Attribute Name in get_grade: In your __init__ method, you stored the midterm score in self.mid, but tried to access self.midterm in get_grade—this will throw an AttributeError because that attribute doesn't exist.
  • Mismatched String Formatting in getStudentData: You used the float format specifier %7.1f to print gradeletter, which is a string (like "A" or "B"). This will cause a TypeError since you can't format a string as a float.
  • Bonus: Overly Broad Exception Catch: Your current try-except block catches all exceptions, which can hide unexpected issues. It's better to target specific exceptions (like TypeError if scores might be non-numeric) instead.

Fixed Code

Here's the corrected version of your class with explanations for each change:

class StudentClass(object):
    def __init__(self, sid, name, midterm, final):
        self.id = sid
        self.name = name
        self.mid = midterm
        self.final = final

    def get_grade(self):
        try:
            # Fixed: Use self.mid instead of self.midterm to match __init__
            average = (self.mid + self.final) / 2
            if average >= 90:
                return "A"
            elif 80 <= average < 90:
                return "B"
            elif 70 <= average < 80:
                return "C"
            elif 60 <= average < 70:
                return "D"
            else:
                return "F"
        # Improved: Catch only specific exceptions to avoid hiding unexpected errors
        except TypeError:
            print("Error: Midterm or final score is not a numeric value.")
            return None  # Return a value to prevent crashes in getStudentData

    def getStudentData(self):
        gradeletter = self.get_grade()
        # Fixed: Use string format specifier %7s for the letter grade
        # Added a check to handle cases where get_grade returns None due to error
        if gradeletter is not None:
            return "%-4s %-15s %5d %5d %7s" % (self.id, self.name, self.mid, self.final, gradeletter)
        else:
            return "%-4s %-15s %5d %5d %7s" % (self.id, self.name, self.mid, self.final, "ERROR")

Key Changes Explained

  1. Attribute Fix: Swapped self.midterm to self.mid in get_grade to align with the attribute set in your constructor.
  2. Formatting Fix: Changed %7.1f to %7s in getStudentData to properly format the letter grade string.
  3. Exception Handling Tweak: Narrowed the except block to catch only TypeError (triggered if non-numeric scores are passed) and added a return None so getStudentData can handle errors gracefully.
  4. Error Gracefulness: Added a check for None from get_grade to display "ERROR" instead of crashing if there's a score issue.

Example Usage

Test the corrected class with this snippet:

# Create a valid student instance
student1 = StudentClass("S001", "Alice Smith", 85, 92)
print(student1.getStudentData())

# Test with a non-numeric score to trigger error handling
student2 = StudentClass("S002", "Bob Jones", "seventy", 80)
print(student2.getStudentData())

This will output:

S001 Alice Smith        85    92       A
Error: Midterm or final score is not a numeric value.
S002 Bob Jones          seventy    80    ERROR

内容的提问来源于stack exchange,提问作者user3089144

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 09:12:56