【发布时间】:2021-12-29 20:54:26
【问题描述】:
我收到一个 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!")
【问题讨论】:
-
punk = random.choice(words[text_punk])那行代码在 if/else 之前。 -
你在
if条件之前访问它,这就是它应该抛出错误的地方 -
非常感谢@JohnGordon 和 shriakhilc 的帮助,非常感谢...我快要疯了!
标签: python dictionary random input keyerror