deans7
deans7

Reputation: 29

try- except- else- finally

got a piece of code which I'm trying to solve. I am really close but for some reason the else statement is printing out at wrong time I'm not sure whats wrong with it.

 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() 

When i type ex01 as input, it prints out 130 and invalid when it shouldn't print out invalid. Any ideas whats wrong?

Upvotes: 0

Views: 2282

Answers (1)

DevLounge
DevLounge

Reputation: 8437

This is the way to do:

 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

Upvotes: 4

Related Questions