python - Sentinel while 循环结束时显示哨兵值

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

当我输入 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/

相关文章:

python - 求矩阵内 1s 的最大平方时出错

python - 使用 Python 将文本文件写入 SQL

python - 在python中找到特定字符串后如何打印所有行?

python - 删除 Python 打印行中的字符

Python:将列表分成变量

python - 使用python在字符串中创建一个tar文件

python - 如何替换或编辑 django rest 框架路由器中的查找参数?

python - 在 x64 架构上获得心理加速?

python - 如何打印从 'startswith' 到 'endswith' 的字符串部分

python - 值错误: Classification metrics can't handle a mix of unknown and binary targets?