我正在制作更改计数器,而且我在打印等级的百分比时遇到问题,每当我运行程序时,我可以输入尽可能多的输入,但是,当我输入完成时,应该终止程序并给用户留下百分比和字母等级,它只是结束程序。如果我能得到任何建议,我将不胜感激。 这是我的代码:
grade=""
total=0
count=1
scores=''
while scores != 'done':
scores=input("Enter Homework score: ")
if scores.isdigit():
numeric=int(scores)
percentage=(numeric*10/count)
elif percentage >= 92 and percentage < 100:
letter = 'A'
elif percentage >= 87 and percentage < 92:
letter = 'B+'
elif percentage >= 80 and percentage < 87:
letter = 'B'
elif percentage >=77 and percentage < 80:
letter = 'C+'
elif percentage >=70 and percentage < 77:
letter = 'C'
elif percentage >= 67 and percentage < 70:
letter = 'D+'
elif percentage >= 60 and percentage < 67:
letter = 'D'
elif percentage < 60 and percentage >= 0:
letter= 'F'
elif (numeric) < 0:
print("Score must be between 0 and 10")
elif (numeric) > 10:
print("Score must be between 0 and 10")
elif (scores)== 'done':
print(percentage,"% and you got an, ",letter)
答案 0 :(得分:2)
您的条件逻辑存在缺陷。如果letter
:
score.isdigit()
)
while scores != 'done':
scores=input("Enter Homework score: ")
if scores.isdigit():
numeric=int(scores)
percentage=(numeric*10/count)
if percentage >= 92 and percentage < 100:
letter = 'A'
elif percentage >= 87 and percentage < 92:
letter = 'B+'
...
如果初始条件为假,则跳出循环通常更清晰,例如:
while scores != 'done':
scores=input("Enter Homework score: ")
if not scores.isdigit():
continue
numeric=int(scores)
percentage=(numeric*10/count)
if 92 <= percentage < 100:
letter = 'A'
elif 87 <= percentage < 92:
letter = 'B+'
...
同样在python中,你不应该害怕例外。 python中常见的习语是EAFP(比宽容更容易要求宽恕):
while scores != 'done':
scores=input("Enter Homework score: ")
try:
numeric = int(scores)
except ValueError:
continue
您可能还想考虑更好的方法来执行大成绩if
elif
elif
...阻止。例如。另一种方法是定义成绩词典:
grades = {'A': (92, 100), 'B+': (87, 92)} # Etc..
score = 93
_, letter = max((low <= score < high, letter) for letter, (low, high) in grades.items())
print(letter) # 'A'
答案 1 :(得分:1)
您的代码应类似于下面的代码。虽然我仍然无法评估你的程序背后的逻辑(因为你没有在你的问题中解释,例如percentage=(numeric*10/count)
对我来说似乎不太正确,等等),但下面的代码解决了你当前的问题(基于你当前的问题)。
grade=""
total=0
count=1
scores=''
percentage = 0
while scores != 'done':
scores=input("Enter Homework score: ")
if scores.isdigit():
numeric=int(scores)
if numeric < 0:
print("Score must be between 0 and 10")
elif numeric > 10:
print("Score must be between 0 and 10")
percentage=(numeric*10/count)
if percentage >= 92 and percentage < 100: # I would change this to if percentage >= 92 and percentage <= 100:
letter = 'A'
elif percentage >= 87 and percentage < 92:
letter = 'B+'
elif percentage >= 80 and percentage < 87:
letter = 'B'
elif percentage >=77 and percentage < 80:
letter = 'C+'
elif percentage >=70 and percentage < 77:
letter = 'C'
elif percentage >= 67 and percentage < 70:
letter = 'D+'
elif percentage >= 60 and percentage < 67:
letter = 'D'
elif percentage < 60 and percentage >= 0: #I would change this to else:
letter= 'F'
print(percentage,"% and you got an, ",letter)