Below is the code I came up with for EX48. Rather than creating a try-except statement, I wrote a mini for-loop with an if-else statement. For some reason I feel like this is a hacky way. Works great and doesn’t puke Value Errors from any tests I did. Is this acceptable or is try-except recommended in situations like this?
lexicon = {'north': 'direction',
'south': 'direction',
'east': 'direction',
'west': 'direction',
'down': 'direction',
'up': 'direction',
'left': 'direction',
'right': 'direction',
'back': 'direction',
'go': 'verb',
'kill': 'verb',
'eat': 'verb',
'the': 'stop',
'in': 'stop',
'of': 'stop',
'from': 'stop',
'at': 'stop',
'it': 'stop',
'door': 'noun',
'bear': 'noun',
'princess': 'noun',
'cabinet': 'noun',
1234: 'number',
3: 'number',
91234: 'number'
}
user_input = input('> ')
def check_input(split_words):
new_list = []
for i in split_words:
if i.isdigit():
new_list.append(int(i))
else:
new_list.append(i)
return new_list
def scan(sentence):
results = []
split_words = sentence.split()
checked_list = check_input(split_words)#checks and converts user input numbers to integers
for word in checked_list:
get_type = lexicon.get(word)
if get_type == None:
results.append(('error', word))
else:
results.append((get_type, word))
print(results)
scan(user_input)