簡體   English   中英

KeyError:字典和輸入

[英]KeyError: Dictionary and Input

我收到一個 KeyError。 else塊不起作用。 當輸入超出字典時,它會不斷給出 KeyError,但是它應該print("problem")

如果您知道解決此問題的方法,請告訴我。 謝謝你。

words = {"good night": ["nighty night", "good night", "sleep well"],
         "good morning": ["good morning", "wakey-wakey!", "rise and shine!"]}

text_punk = input("text something: ")

punk = random.choice(words[text_punk])


if text_punk in words:
    print(punk)
    talk(punk) #this is for pyttsx3
else:
    print("problem!")

在此代碼中,在您檢查if text_punk in words之前引發了異常:

punk = random.choice(words[text_punk])  # might raise

if text_punk in words:
    print(punk)
    talk(punk) #this is for pyttsx3
else:
    print("problem!")

您可以通過在分配punk之前檢查words來修復它:

if text_punk in words:
    punk = random.choice(words[text_punk])  # shouldn't raise
    print(punk)
    talk(punk) #this is for pyttsx3
else:
    print("problem!")

或使用try/except而不是if/else

try:
    punk = random.choice(words[text_punk])  # might raise
    print(punk)
    talk(punk) #this is for pyttsx3
except KeyError:
    print("problem!")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM