随函附上我想回答的问题的副本。 (它不是家庭作业btw,只是来自编程电子书)。
所以,首先,我创建了字典。
fridge ={ "steak" : "it is so yum!" , \
"Pizza" : "it is even yummier!" , \
"eggs": "always handy in a pinch" , \
"ice cream": "a tasty treat for when I work hard" , \
"butter" : "always useful for spreading on toast" \
}
不得不承认,也许这就是文字措辞的方式,用句子来说:
“然后创建一个名称,该名称引用包含食物名称的字符串,名称为food_sought
我非常困惑。我认为这意味着:
创建一个名为food_sought的变量,使其等于冰箱字典中的任何键....然后使用for循环查看字典中是否存在匹配。
左右....
food_sought = "steak"
for food_sought in fridge:
if food_sought !=steak:
print ("there has not been a match!")
每当我运行代码时,我都被告知:
追踪(最近一次通话): 文件“”,第2行,in if food_sought == steak: NameError:名称'steak'未定义
答案 0 :(得分:2)
steak
将是一个变量。
你要求的是:
food_sought != 'steak'
但你可能想要的是
key != food_sought
见下文
如果你想要这个值,你可以在python3中使用items()
或在python 2中使用iteritems()
food_sought = 'steak'
for key, value in fridge.items():
if key != food_sought:
print("Not the key we're looking for...")
print(key) # the key, ie "steak'
print(value) # the value, ie "it is so yum!" -- I agree
牛肉是什么晚餐。
答案 1 :(得分:1)
以下是如何使用for循环对字典进行操作,希望它能帮助您更好地理解:)
fridge ={ "steak" : "it is so yum!" , \
"Pizza" : "it is even yummier!" , \
"eggs": "always handy in a pinch" , \
"ice cream": "a tasty treat for when I work hard" , \
"butter" : "always useful for spreading on toast" \
}
food_sought = "steak"
for key, value in fridge.items():
if(key == food_sought):
print(key, 'corresponds to', value)
else:
print ("There has not been a match!")
输出:(注释词典未订购)
There has not been a match!
There has not been a match!
There has not been a match!
There has not been a match!
steak corresponds to it is so yum!
试试here
答案 2 :(得分:0)
问题是牛排是一个变量,你没有定义。
当您编写food_sought!=steak
时,您正在比较两个变量的值,但未定义变量牛排。
您的第一行代码错误地指定了food_sought="steak"
,它应该分配steak='steak'
。这样你的代码就可以了:
steak = "steak"
for food_sought in fridge:
if food_sought != steak:
print ("there has not been a match!")
话虽如此,你如何编写代码并不是最好/最好的方式,尽管它有效。无需定义变量steak
,您可以直接将food_sought
变量与字符串'steak'
进行比较。
代码如下所示:
for food_sought in fridge:
if food_sought != 'steak':
print ("there has not been a match!")