Skip to main content
 首页 » 编程设计

python之简化,打印文本而不是 bool 值,Python

2025年04月02日14tuyile006

使用 python 对学生成绩进行评分。试图从中简化

A = ((float(scptratio)) >= (0.9) and (float(scptratio) <= 1)) 
B = ((float(scptratio)) >= (0.8) and (float(scptratio) <= (0.89))) 
 
if A == True: 
print (studentname, (" has scored an A on the test.")) 
 
elif B == True: 
print (studentname, (" has scored an B on the test.")) 
 
elif C == True: 
    print (studentname, (" has scored an C on the test.")) 

等类似于

A = (((float(scptratio)) >= (0.9) and (float(scptratio) <= 1)), "A") 
B = (((float(scptratio)) >= (0.8) and (float(scptratio) <= (0.89))), "B") 
 
Pass = [A, B, C, D] 
 
 
if Pass: 
    print (studentname, "passed the test with a coefficient of", scptratio, ("scoring a grade of {}".format(Pass))) 
elif F: 
    print (studentname, "has failed the test.") 
 
else: 
    print ("Error! Negative value entered.") 

我如何让它打印实际的字母分数而不是 bool 值?

请您参考如下方法:

我建议制作一个易于编辑的列表,其中包含特定等级所需的最低分数,从高到低:

minimum_scores = [("A", 9), ("B", 8), ("C", 7), ("D", 6)] 

然后浏览此列表并打印学生通过的第一年级。

for grade, score in minimum_scores: 
    if float(scptratio) >= score: 
        print(studentname, "passed the test with a coefficient of", str(scptratio), "scoring a grade of", grade) 
        break 
else: #No break hit, so the student didn't pass any of the minimum requirements. 
    print(studentname, "has failed the test.")