0

我正在尝试在字典中查找一些食物,如果找不到食物,我想调用 else 语句,但是由于某些原因,当找不到食物时,最后一个键和它在字典中的值被打印出来。我需要你的帮助,拜托。

fridge = {"cheese" : "so delicious", "crackers": "you will love it once you try it", "chicken soup": "delicous stuff"}
food_sought = "pepper"
if food_sought:
    for food_sought in fridge:
        print("I was able to find a something in our list of food: %s : %s" % (food_sought, fridge[food_sought]))
        break
    else:
        print("We couldn't find the food you were looking for")
4

2 回答 2

1

您应该使用if而不是for

fridge = {"cheese" : "so delicious", "crackers": "you will love it once you try it", "chicken soup": "delicous stuff"}
food_sought = "pepper"
if food_sought in fridge:
    print("I was able to find a something in our list of food: %s : %s" % (food_sought, fridge[food_sought]))
else:
    print("We couldn't find the food you were looking for")

如果确实需要使用for .. in ..,请使用不同的变量名。或者food_sought被覆盖。

fridge = {"cheese" : "so delicious", "crackers": "you will love it once you try it", "chicken soup": "delicous stuff"}
food_sought = "chicken"
for name in fridge:
    if name == food_sought:
        print("I was able to find a something in our list of food: %s : %s" % (food_sought, fridge[food_sought]))
        break
else:
    print("We couldn't find the food you were looking for")
于 2013-09-27T16:36:53.263 回答
0

如果你必须使用for ... in,那么要走的路就是这个。

fridge = {"cheese" : "so delicious", "crackers": "you will love it once you try it", "chicken soup": "delicous stuff"}
food_sought = "pepper"

found = False
for food in fridge:
    if food == food_sought:
        found = True

if found:
    print('{} found'.format(food_sought))
else:
    print('{} not found'.format(food_sought))

在开始循环之前将标记设置为foundFalse如果您在循环中的某处找到食物,请将标记设置为True。检查循环后的条件。

break如果找到食物,您可以通过离开循环来优化代码。

于 2013-09-27T16:46:33.450 回答