首页 > 解决方案 > 如何阻止代码在python中走得更远

问题描述

这是我到目前为止编写的代码:-

# checking for the valididy of the marks entered 
def read_marks(quiz, exam, assignment, project):
    if quiz < 0:
        print("ERROR: Invalid Marks", quiz, "< 0")
    elif quiz > 20:
        print("ERROR: Invalid Marks", quiz, "> 20")
    elif exam < 0:
        print("ERROR: Invalid Marks", exam, "< 0")
    elif exam > 100:
        print("ERROR: Invalid Marks", exam, "> 100")
    elif assignment < 0:
        print("ERROR: Invalid Marks", assignment, "< 0")
    elif assignment > 100:
        print("ERROR: Invalid Marks", assignment, "> 100")
    elif project < 0:
        print("ERROR: Invalid Marks", project, "< 0")
    elif project > 50:
        print("ERROR: Invalid Marks", project, "> 50")
    else:
        return quiz, exam, assignment, project


# computing GPA of the valid marks
def compute_gpa(quiz, exam, assignment, project):
    a_wei = float(15)
    b_wei = float(40)
    c_wei = float(20)
    d_wei = float(25)
    GPA = ((quiz / 20 * a_wei) + (exam / 100 * b_wei) + (assignment / 100 * c_wei) + (project / 50 * d_wei)) / 10
    GPA = round(GPA, 2)
    return GPA


# assigning grade according to the GPA
def assign_grade(gpa):
    if gpa == 10:
        return "O"
    elif gpa <= 4:
        return "F"
    elif gpa >= 9 and gpa < 10:
        return "A"
    elif gpa >= 8 and gpa < 9:
        return "B"
    elif gpa >= 6 and gpa < 8:
        return "C"
    elif gpa >= 5 and gpa < 6:
        return "D"
    elif gpa >= 4 and gpa < 5:
        return "E"


def main():
    # take input and call functions
    a = int(input())
    b = int(input())
    c = int(input())
    d = int(input())

    x,l,m,r = read_marks(a, b, c, d)
    q = compute_gpa(x,l,m,r)
    v = q
    s = assign_grade(v)

    print("The GPA is " + str(q) + ", and the Grade is " + str(s))

if __name__ == "__main__":
    main()

所以我的任务是我必须接受 4 个输入,然后检查它们的有效性,然后计算它们的 GPA,然后打印出它们的成绩。此代码适用于已经在其限制范围内的数字,但如果有人输入超出其限制的数字,它会打印我希望它打印的内容,但它也在尝试计算我正在打印的错误的 GPA。请帮忙,因为我也尝试过引发异常,但它没有用。

标签: pythonpython-3.x

解决方案


您可以像这样在 read_marks 函数中引发异常,而不是打印错误:

# checking for the valididy of the marks entered 
def read_marks(quiz, exam, assignment, project):
    if quiz < 0:
        raise Exception("ERROR: Invalid Marks", quiz, "< 0")
    elif quiz > 20:
        raise Exception("ERROR: Invalid Marks", quiz, "> 20")
    elif exam < 0:
        raise Exception("ERROR: Invalid Marks", exam, "< 0")
    elif exam > 100:
        raise Exception("ERROR: Invalid Marks", exam, "> 100")
    elif assignment < 0:
        raise Exception("ERROR: Invalid Marks", assignment, "< 0")
    elif assignment > 100:
        raise Exception("ERROR: Invalid Marks", assignment, "> 100")
    elif project < 0:
        raise Exception("ERROR: Invalid Marks", project, "< 0")
    elif project > 50:
        raise Exception("ERROR: Invalid Marks", project, "> 50")
    else:
        return quiz, exam, assignment, project

推荐阅读