无法在python程序中定义我的变量

2024-05-19 20:54:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要制作一个函数,提供一个学期总结,其中包括所修课程、所修学分、GPA分数和学期GPA。我有第一个功能在工作

-gpacalc()

但是,当我尝试创建第二个函数时

-课程点(学分、年级)

当你输入一个班级的学分和收到的成绩时,它应该返回一个特定班级的“GPA分数”。 这就是我遇到问题的地方它说“gp”没有定义。我知道这是很多,但我认为这可能是一个简单的错误。我可能在跟踪我的变量,但我仍然不太清楚。如果你能帮忙,我很感激

# coursePoints requirement
def coursePoints(credit, grade):
    gp = 0.00
    totalcredits = 0
    totalpoints = 0
    # I have lots of if statements here, I deleted them for simplicity.#
    gp = round(totalpoints,2)/round(totalcredits)

print("The GPA points of this class is:", round(gp))

coursePoints(3,"b")

Tags: of函数功能分数课程学分学期gp
1条回答
网友
1楼 · 发布于 2024-05-19 20:54:29

您必须在print("The GPA points of this class is:", round(gp))上添加一个缩进,使其位于函数coursePoints()的定义内

如果没有缩进,就好像您试图在文件中打印一个没有给定任何值、也没有声明的变量

此外,如果您在coursePoints()中输入“b”而不是“b”,则根据最后一行,它将返回0的GPA,因为您只指定了大写字母。或者,您可以使用if grade in ["B","b"]:在if中添加分析bot字母的选项。或者一个更简单的解决方案是在grade = grade.upper()的正下方添加def coursePoints(credit, grade):,并保持其他所有内容不变(wjandrea的道具)

代码的结尾应为:

[...]
    elif grade in ["D-","d-"]:
        totalpoints = totalpoints + (credit * .67)
        totalcredits = totalcredits + credit
    else:
        totalpoints = totalpoints + (credit * 0)
        totalcredits = totalcredits + credit
    gp = round(totalpoints,2)/round(totalcredits)
    # next line is indented now, thus, inside coursePoints()
    print("The GPA points of this class is:", round(gp))

coursePoints(3,"b") # change if condition for elif grade in ["B","b"]:

编辑:根据wjandrea的评论进行更正和扩展

相关问题 更多 >