python - 使用字典尝试并排除异常(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")
解决方案
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")
推荐阅读
- shell - 如何使用 shell 通过 scp 连接而无需密码?
- python - 用新行将列表写入csv,迭代中不重复
- swift - 使用可选初始化程序在@AppStorage 中存储自定义数据类型?
- javascript - 如何在 Angular 中使用 ngx-dropzone 上传单个文件?
- linux - 内核日志中的内存分配失败是什么意思?
- amazon-web-services - 我可以在 AWS SageMaker Ground Truth NER 中使用预先标记的数据吗?
- r - 删除所有列没有值的行
- javascript - Next.js - 刷新页面时加载不会关闭
- pine-script - 基于条目 ID 的条目上限
- angular - 在 Angular 2+ 中存储订阅时是否使用了特定的前缀或后缀?