3 回答

TA貢獻(xiàn)1887條經(jīng)驗(yàn) 獲得超5個(gè)贊
試試這個(gè):
items = {'1': '2', '3': '4', '5': '6'}
while True:
choice = input("Select your item: ")
print(choice)
if choice in items:
the_choice = items[choice]
print("You chose",the_choice)
break
print("Uh oh, I don't know about that item")

TA貢獻(xiàn)1866條經(jīng)驗(yàn) 獲得超5個(gè)贊
只是從您的代碼中忽略不是關(guān)鍵字
items = {'1': '2', '3': '4', '5': '6'}
choice = input("Select your item: ")
print(choice)
for choice in items:
if choice in items:
the_choice = items[choice]
print("You chose",the_choice)
break
else:
print("Uh oh, I don't know about that item")

TA貢獻(xiàn)1995條經(jīng)驗(yàn) 獲得超2個(gè)贊
讓我們來看看為什么當(dāng)它不應(yīng)該工作完全忽視了語法部分:
items由組成{'1': '2', '3': '4', '5': '6'}。itemssay的補(bǔ)碼citems應(yīng)包含所有字符串,但不包括items。
for not choice in items就像在說for choice in citems。對(duì)于解釋器來說這沒有意義,因?yàn)樵谶@里定義這么大的集合確實(shí)是一個(gè)問題。
但是,您的問題可以通過以下方法解決:
items = {'1': '2', '3': '4', '5': '6'}
choice = input("Select your item: ")
while choice not in items:
print("Uh oh, I don't know about that item")
choice = input("Select your item: ")
the_choice = choice #assuming you want to place the value of `choice` in `the_choice` for some reason
print("You chose",the_choice)
添加回答
舉報(bào)