a = 4.0
b = 3.0
c = 2.0
d = 1.0
f = 0.0
counter = 0
gpa = 0
while True:
grade = input("what is your grade ")
if(grade == "A" or "a"):
counter += 1
gpa += a
elif(grade == "B" or "b"):
counter += 1
gpa += b
elif(grade == "C" or "c"):
counter += 1
gpa += c
elif(grade == "D" or "d"):
counter += 1
gpa += d
elif(grade == "F" or "f"):
counter += 1
gpa += f
elif (grade == ""):
finalgrade = (gpa/counter)
print(finalgrade)
break
else:
print ("invalid input")
所以我一直在尝试这项工作,但无论我做什么,我都无法弄清楚...... 当我使用调试器时,它没有多大帮助,但它说它正好超过了所有的elif语句
答案 0 :(得分:1)
此:
if grade == "A" or "a"
不是真的按照你的想法去做。由于python中的运算符优先级,它计算grade=="A"
,然后计算or
到"a"
。这将始终评估为True
。
请改用in
运算符:
if grade in ("A", "a"):
或者,甚至更好:
if grade.lower() == "a":
答案 1 :(得分:0)
而不是
grade == "A" or "a" #always True, since "a" is truthy
使用
grade == "A" or grade == "a"
或
grade.upper() == "A"
同样更改其他陈述。
虽然我会这样做
import itertools
points = {'A':4, 'B':3, 'C':2, 'D':1, 'F':0}
total = 0.
for count in itertools.count():
grade = input('What is your grade ')
if not grade:
break
try:
total += points[grade]
except KeyError:
print('invalid input')
print(total / count)