首页 > 解决方案 > Python 程序 - 使用 while 循环根据用户输入计算字母等级的数量

问题描述

我为以下问题编写了一些代码:

“编写一个程序,不断询问用户考试分数,以 0 到 100 范围内的整数百分比形式给出。计算每个字母等级类别中的总成绩如下:90 到 100 是 A,80 到 89 是B,70到79是C,60到69是D,0到59是F循环,所以不要在计算中使用它。)”

这是我的代码:

count = 0
gradeA = 0
gradeB = 0
gradeC = 0
gradeD = 0
gradeF = 0

score = int(input("Enter an exam score: "))
while score != -1:
    count = count + 1
    score = int(input("Enter an exam score: "))

if score >= 90 and score <= 100:
    gradeA = gradeA + 1
elif score >= 80 and score <= 89:
    gradeB = gradeB + 1
elif score >= 70 and score <= 79:
    gradeC = gradeC + 1
elif score >= 60 and score <= 69:
    gradeD = gradeD + 1
elif score >= 0 and score <= 59:
    gradeF = gradeF + 1

print ("You entered " + str(count) + " exam scores.")
print ("Number of A's = " + str(gradeA))
print ("Number of B's = " + str(gradeB))
print ("Number of C's = " + str(gradeC))
print ("Number of D's = " + str(gradeD))
print ("Number of F's = " + str(gradeF))

问题是当我运行代码时,每个字母等级类别中的等级数都显示为 0。我该如何解决这个问题以便显示正确的数字?

标签: python

解决方案


你忘了缩进你的 if 语句。

count = 0
gradeA = 0
gradeB = 0
gradeC = 0
gradeD = 0
gradeF = 0

score = int(input("Enter an exam score: "))
while score != -1:
    count = count + 1
    score = int(input("Enter an exam score: "))

    if score >= 90 and score <= 100:
        gradeA = gradeA + 1
    elif score >= 80 and score <= 89:
        gradeB = gradeB + 1
    elif score >= 70 and score <= 79:
        gradeC = gradeC + 1
    elif score >= 60 and score <= 69:
        gradeD = gradeD + 1
    elif score >= 0 and score <= 59:
        gradeF = gradeF + 1

print ("You entered " + str(count) + " exam scores.")
print ("Number of A's = " + str(gradeA))
print ("Number of B's = " + str(gradeB))
print ("Number of C's = " + str(gradeC))
print ("Number of D's = " + str(gradeD))
print ("Number of F's = " + str(gradeF))

推荐阅读