try- except- else- finally

时间:2016-03-20 22:11:04

标签: python-3.x exception

得到了一段我正在努力解决的代码。我非常接近,但由于某种原因,其他声明在错误的时间打印出来我不确定它是否有错。

 try:
   my_dict = {'ex01': 65, 'ex02': 'hello', 'ex03': 86, 'ex04': 98}
   key_str = input('Enter a key:') 
   result = my_dict[key_str] 
   result *= 2 
   print(result)
except:
    print("Key not found") 
else:
    print("invalid")
finally: 
    print() 

当我输入ex01作为输入时,它打印出130并且当它不应该打印出来时无效。任何想法都错了吗?

1 个答案:

答案 0 :(得分:4)

这是要做的事情:

 my_dict = {'ex01': 65, 'ex02': 'hello', 'ex03': 86, 'ex04': 98}
 key_str = input('Enter a key:') 

 try:
   result = my_dict[key_str] 
   result *= 2 
except KeyError:  # the key does not exist
    print('Key not found') 
except:  # something else went wrong
    print('invalid')
else:  # everything went fine
    print(result)
finally: 
    print('the end')  # Will always be executed