首页 > 解决方案 > 如何防止哨兵值与输入冲突?

问题描述

我正在学习初学者 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 循环并稍后打印这两个语句?

谢谢你。

标签: pythonwhile-loop

解决方案


推荐阅读