前哨while循环在结束时显示前哨值

时间:2020-01-24 04:07:18

标签: python

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

1 个答案:

答案 0 :(得分:0)

练习“不要重复自己”的风格总是好的。另外,在接受用户输入时要保持一点防御性-如果用户输入了无法转换为浮点数的内容,应该怎么办?

人们可以反复要求成绩,并尝试将答案转换为浮点数并进行计算。如果无法将用户输入转换为浮点,则请检查其是否为“停止”-如果是,则打印平均值,然后打印,否则打印该输入值是不允许的。

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') 
相关问题