total = 0
count = 0
grade = input("Enter the grade between 0 and 100 or type stop to display average: ")
while grade != "stop":
x = float(grade)
total += x
count += 1
grade = input("Enter the grade between 0 and 100 or type stop to display average: ")
average = total/count
print(f'\nYour average grade is {average}')
当我输入 stop 时,我不希望在最后一个输入旁边打印 stop。
我当前的输出是:
Enter the grade between 0 and 100 or type stop to display average: 10
Enter the grade between 0 and 100 or type stop to display average: 50
Enter the grade between 0 and 100 or type stop to display average: 100
Enter the grade between 0 and 100 or type stop to display average: stop
Your average grade is 53.333333333333336
最佳答案
练习“不要重复自己”的风格总是好的。在接受用户输入时也不要采取防御措施 - 如果用户输入无法转换为 float 的内容会发生什么?
可以反复询问成绩并尝试将答案转换为 float 并进行计算。如果用户输入无法转换为 float ,则检查它是否为“停止” - 如果是,则打印平均值并中断,否则打印不允许输入的值。
total = 0
count = 0
while True:
grade = input('Enter the grade between 0 and 100 or type "stop" to display average: ')
try:
total += float(grade)
count += 1
except ValueError:
if grade.lower() == 'stop':
print(f'Your average grade is {total/count:.2f}')
break
else:
print(f'Input {grade!r} is not allowed')
关于python - Sentinel while 循环结束时显示哨兵值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59890239/