try- except- else- finally
有一段代码,我正试图解决。我真的很接近,但是由于某种原因,其他的陈述在错误的时间打印出来,我不确定它有什么问题。
1 2 3 4 5 6 7 8 9 10 11 12 | 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 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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 |