python - 哨兵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
解决方案
练习“不要重复自己”的风格总是一件好事。在接受用户输入时也要少做防御——如果用户输入的东西不能转换成浮点数,会发生什么?
可以反复询问成绩,并尝试将答案转换为浮点数并进行计算。如果用户输入无法转换为浮点数,则检查它是否为“停止” - 如果是,则打印平均值并中断,否则打印输入的值是不允许的。
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')
推荐阅读
- kubernetes - 将 pod 名称添加到 fluentd 中的事件标签
- javascript - 如何从 Nativescript Angular 中的联系人获取电话号码?
- php - 数据库中的错误值
- java - 在 Java 中使用 Xpath 定位具有特定命名空间的元素
- python - 当一个numpy数组被切片时,有没有办法不制作副本?
- javascript - JS中console.log('any string or statement'+ object)和console.log('any string or statement', object)的区别?
- php - 具有基本 php 形式的 DropzoneJs
- angularjs - 如何使用 && 显示 ng-checked 条件
- javascript - javascript - 发送了 2 个承诺,第二个承诺的结果排在第一位 - 如何处理?
- c# - 如何在 C# 中正确反序列化 JSON