Reputation: 109
I have a dictionary with certain items. I want to accept the key input from the user and display the corresponding item. However if the user enters the wrong key which is not defined in the dictionary, it throws key error exception.
I want the code to go back to the line end execute from where the command for user input is written if key error exception occurs.
I have used try except statements but shows an error. Please help me to fix this.
Below is my code:
a={'name':'pav','q1':'y','age':26}
try:
k=input()
print (a[k])
except KeyError:
continue
Upvotes: 1
Views: 1998
Reputation: 1
This can be done in two ways, either by setting the number of try limits or with an infinite loop.
Below is an example for 3 try limits, for an infinite loop you can replace for loop with while.
a={'name':'pav','q1':'y','age':26}
for i in range(3):
k = input()
if k in a:
print(a[k])
break
else:
print('Please enter the valid value')
Upvotes: 0
Reputation: 121
there is a simpler way if you don't want to use a try and except
Simply use dict.get(key) if the key exists it returns its value otherwise it will return None and you can simply check that value:
key=input()
value = dict.get(key)
while value == None:
key=input()
value = dict.get(key)
print value
Upvotes: 1