首页 > 解决方案 > 哨兵while循环结束时显示哨兵值

问题描述

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}')

当我输入停止时,我不想在最后一个输入旁边打印停止。

我目前的输出是:

输入 0 到 100 之间的等级或键入 stop 以显示平均值:10

输入 0 到 100 之间的等级或键入 stop 以显示平均值:50

输入 0 到 100 之间的等级或键入 stop 以显示平均值:100

输入 0 到 100 之间的等级或键入 stop 以显示平均值:stop

你的平均成绩是 53.333333333333336

标签: python

解决方案


练习“不要重复自己”的风格总是一件好事。在接受用户输入时也要少做防御——如果用户输入的东西不能转换成浮点数,会发生什么?

可以反复询问成绩,并尝试将答案转换为浮点数并进行计算。如果用户输入无法转换为浮点数,则检查它是否为“停止” - 如果是,则打印平均值并中断,否则打印输入的值是不允许的。

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') 

推荐阅读