[英]Problems with Dictionary Python3
我目前正在做一個猜謎游戲任務。 該作業使用字典來存儲作為鍵的課程名稱和作為值的課程編號。 用戶猜測給定課程名稱的課程編號。 如果該值與鍵匹配,則應打印“正確”。 反之亦然。
我已經讓程序一次顯示一個鍵,輸入語句將它們分開。 我已經讓正確/不正確的計數器工作了。 我無法讓 if 語句正常工作,該語句應該檢查值是否與鍵匹配。 無論答案是否正確,它每次都打印不正確。 我意識到 if 語句的條件可能有問題,因為我不確定如何一次提取一個值。
這是我到目前為止所擁有的:
# Mainline
def main():
programming_courses={"Computer Concepts":"IT 1025",\
"Programming Logic":"IT 1050",\
"Java Programming":"IT 2670",\
"C++ Programming":"IT 2650",\
"Python Programming":"IT 2800"}
print ("Learn your programming courses!\n")
correct=0
incorrect=0
v=0
# Game Loop
for key in programming_courses.keys():
print(key)
answer = input("Enter the Course Number: ")
if answer != programming_courses.values():
print("Incorrect")
incorrect += 1
else:
print("Correct!")
correct += 1
# Display correct and incorrect answers
print ("You missed ",incorrect," courses.")
print ("You got ",correct," courses.\n")
# Entry Point
response=""
while (response!="n"):
main()
response=input("\n\nPlay again?(y/n)\n# ")
你的問題是當你檢查你的聽寫時。 目前,您的代碼正在將答案與字典中所有值的列表進行比較:
out[]:
dict_values(['IT 1025', 'IT 1050', 'IT 2670', 'IT 2650', 'IT 2800'])
如果您更改為以下內容,則可以通過使用給定鍵從 dict 中獲取特定值:
for key in programming_courses.keys():
print(key)
answer = input("Enter the Course Number: ")
if answer != programming_courses[key]:
print("Incorrect")
incorrect += 1
else:
print("Correct!")
correct += 1
你的問題在這里:
if answer != programming_courses.values():
programming_courses.values()
是字典中所有值的列表。 如果您不了解程序中發生了什么,那么將內容打印出來並查看它是否符合您的預期會很有幫助。
您想要的是您現在所在key
的特定值,您需要從字典中查找,如下所示:
if answer != programming_courses[key]:
此外,迭代 dict 默認情況下會為您提供密鑰,因此您可以說:
for key in programming_courses:
你不需要在那里使用.keys()
。
你可以試試這個
if answer != programming_courses[key]:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.