【发布时间】:2020-03-29 12:18:40
【问题描述】:
对于下面的代码,我应该编写三个单独的 try/except 块,分别对以下三个错误做出反应:
1) 文件不可用 2) 文件中的一行包含的元素数量少于预期 3) 在字典中找不到用户的条目作为键
另外,第二个错误不应该完成程序。文本文件中不正确的行应该被跳过,所以字典应该有三个键值对。 文本文件的内容如下所示。最后,程序应该能够同时打印左词(原词)和右词(翻译):
猎犬
猫卡茨
问号
雪花
这是以下代码:
with open(filename, "r", encoding="utf8") as dictionaryfile:
for line in dictionaryfile:
elements_from_line = line.split()
word = elements_from_line[0]
translation = elements_from_line[1]
translationdictionary[word] = translation
inputword = input("Welches Wort soll übersetzt werden? >")
correct_translation = translationdictionary[inputword]
print("Das Eingabewort:\t{}\nDie Übersetzung:\t{}".format(inputword, correct_translation))
【问题讨论】:
标签: python-3.x function try-catch except