当用户尝试删除不在列表中的值时,如何操作 Try Except

How to do Try Except when a user tries to remove a value that is not in a list

如果我有一个列表 foods = ["a", "b"] 并且我让用户输入他们想要删除的值,它就会从列表中删除。

但是,我想要实现的是 Try Except,如果用户输入的值不在列表中(比如“c”),except 将打印我们的“值不在列表中”。

但是,当我尝试这样做时,它只是给我一个错误。我该如何解决这个问题?

#lets the user takes out any food in the fridge
while True:
    try:
        foodaddition = str(input("Enter foods you want to take out of the fridge (or press Q if you had enough :)) (please note that there must be at least one item in the Fridge): "))
        if str(foodaddition).upper() == "Q" or len(foods) == 1:
            break
    except ValueError:
        print("Item not in fridge")
    foods.remove(foodaddition)
print(foods[a])

如果您真的想使用 try/except,您只需将 foods.remove(foodaddition) 移动到 try 分支即可。

然而,更聪明的方法可能是检查元素是否在列表中,而不需要任何异常处理。查找以下示例:

# Lets the user takes out any food in the fridge
while True:
    # Ask for foods
    foodaddition = str(input("Enter foods you want to take out of the fridge (or press Q if you had enough :)) (please note that there must be at least one item in the Fridge): "))
    if str(foodaddition).upper() == "Q" or len(foods) == 1:
        break
    
    # Check if present, then remove it
    if foodaddition in foods:
        foods.remove(foodaddition)
    else:
        print("Item not in fridge")

print(foods)

foodaddition in foods returns 确实 True 当您要查找的元素在列表中时,False 否则。


顺便说一句,在询问新食物之前,检查列表的长度可能符合您的利益。试试下面的代码:

# Lets the user takes out any food in the fridge
while len(foods) > 1:
    # Ask for foods
    foodaddition = input("Enter foods you want to take out of the fridge (or press Q if you had enough :)) (please note that there must be at least one item in the Fridge): ")
    if foodaddition.upper() == "Q":
        break
    
    # Check if present, then remove it
    if foodaddition in foods:
        foods.remove(foodaddition)
    else:
        print("Item not in fridge")

print(foods)