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))

ループを開始する前にマーカーfoundをに設定します。Falseループのどこかに食べ物が見つかったら、マーカーを に設定しますTrue。ループ後の状態を確認してください。

break食品が見つかった場合にループを終了することで、コードを最適化できます。

于 2013-09-27T16:46:33.450 に答える