'KeyError when user input is misspelled
I have to program a text based game where conditions must be met before the game can end. As long as the user input is spelled correctly the game can be completed. However is there is a spelling error I get a KeyError: 'Whatever the misspelled word is'
I can't figure out how to resolve this issue. I have tried to check if user_input in rooms, I've tried to use try:/except:, I just can't figure it out. Would appreciate if someone could steer me in the right direction!
def main():
current_room = 'Mid Deck'
user_input = None
while user_input != 'Exit': #Check to see if user wants to exit game
print('You are in', current_room + '.' ) #Print list of possible user actions
options = rooms.get(current_room)
for i in options:
print(i, 'is', options[i])
user_input = input('What do you want to do?:').capitalize() #Get user input
if user_input == 'Exit':
print('Sorry you lost!')
elif user_input == 'Checklist': #Command to check which consoles have been activated
print('\n'.join(checklist))
elif user_input == 'Activate': #Command to activate consoles and update dictionary and list to reflect user input
if current_room == 'Bridge':
if win_condition < 7:
print('If you activate the console now')
print('the ships systems will short circuit')
print('and you will never escape the gravity well.')
print('Do you still want to activate? Yes or No?')
user_input = input().capitalize()
if user_input == 'Yes':
print('You have lost the game!')
else:
print('You have left the Bridge.')
current_room = 'Navigation'
else:
print('Congratulations you have escaped the stars gravity well!')
print('Thanks for playing and safe journey home!')
else:
checklist.append(current_room + ' is online.')
rooms[current_room]['Console'] = 'Online'
else:
current_room = rooms[current_room][user_input]
Solution 1:[1]
The KeyError is probably raised when the user input a not defined key in:
current_room = rooms[current_room][user_input]
To handle this issue you have to define which input is valid.
current_room_keys = ['Navigator', ...] #room key that valid
Some pseudo-code:
while user_input != 'Exit': #Check to see if user wants to exit game
user_input = input('What do you want to do?:').capitalize() #Get user input
if user_input == 'Exit':
elif user_input == 'Checklist': #Command to check which consoles have been activated
elif user_input == 'Activate': #Command to activate consoles and update dictionary and list to reflect user input
elif user_input in current_room_keys:
current_room = rooms[current_room][user_input]
else:
print('Please input a valid key')
continue
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Will |
