如何防止哨兵值与输入冲突?

时间:2019-10-05 01:13:34

标签: python while-loop

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

谢谢。

0 个答案:

没有答案