首页 > 解决方案 > 使用字典尝试并排除异常(Python)

问题描述

假设我向用户询问了一个词,如果该词不是字典中的键,那么我想打印“那个词不是字典中的键,再试一次”。我将如何使用 try 和 except 来做到这一点?这就是我到目前为止所拥有的。

dict = {"These": 1, "are": 2, "words": 3}
while True:
    try:
        w = input("Enter a word: ")
    except: 
        print("That word is not a key in the dictionary, try again")
    else:
        print("That word is a key in the dictionary")

标签: pythondictionarytry-except

解决方案


KeyError您可以在访问地图中不存在的键时捕获:

try:
    w = input("Enter a word: ")
    k[w]
except KeyError:
    print("That word is not a key in the dictionary, try again")
else:
    print("That word is a key in the dictionary")

推荐阅读