python - 如何防止哨兵值与输入冲突?
问题描述
我正在学习初学者 python,并且有一个问题我被困住了。
该问题涉及询问用户输入他们采摘的任何数量的蘑菇,输入重量,然后根据用户输入对它们进行分类。为此,需要一个列表和一个 while 循环将输入附加到列表中。
到目前为止,这是我的代码,它可以很好地输入所有用户值,但稍后会卡住。
if __name__ == "__main__":
total_list = []
small = 0
medium = 0
large = 0
while True:
try:
mushroom = int(input("Enter a mushroom weight in grams, or STOP to end. "))
total_list.append(mushroom)
if mushroom <= 100:
small += 1
elif mushroom >= 1000:
large += 1
else:
medium += 1
except STOP:
break
print("The weights you entered were ", total_list)
print("There were", small, "small mushrooms,", medium, "mediums, and", large, "larges.")
错误发生在第 24 行,其中 STOP 与输入要求 int() 冲突。
mushroom = int(input("Enter a mushroom weight in grams, or STOP to end. "))
ValueError: invalid literal for int() with base 10: 'STOP'
如何解决此问题以确保 STOP 是我的哨兵值,并会中断 while 循环并稍后打印这两个语句?
谢谢你。
解决方案
推荐阅读
- nestjs - 如何在 NestJS 中将全局提供程序导入另一个全局提供程序?
- python - 如何在python中调用函数
- docker - 从服务器端(从另一个容器)和从客户端(浏览器)使用相同的 URL 引用 Docker 容器
- sql - 如何从 oracle 中的数据库触发器中获取执行的操作和受影响的表?
- r - data.table:组内值存在的计算条件
- python - 循环熊猫目录
- mysql - SQL 选择仅包含数字的值
- java - Java 流,创建自定义有状态操作
- sql - postgreSQL 每个月购买了多少订阅
- electron - electron-packager 正在打包旧版本文件