Code improvement, Python the hard way ex48 -


i completed exercise after confusion , made code complies tests.

word_types = {    'verb' : ['go', 'kill', 'eat'],    'direction' : ['north', 'south', 'east', 'west'],    'noun' : ['bear', 'princess'],    'stop' : ['the','in','of'] }   def scan(sentance):     listy = []     counter = 0     word in sentance.split():         try:             count = counter             key, value in word_types.iteritems():                 ind in value:                     if ind == word:                         counter += 1                         listy.append((key,ind))             if count == counter:                 raise keyerror         except keyerror:             try:                 value = int(word)                 listy.append(('number',value))             except valueerror:                 listy.append(('error',word))     return listy 

the author wanted use try , excepts, don't feel used them efficiently. better way use them here? also, when try , excepts ideal? other tips improving code welcomed.

i assume referring exercise in http://learnpythonthehardway.org/book/ex48.html

the author says use try , except "cheat" @ interpreting numbers because, generally, common way use regular expressions. using int() function attempt convert unknown words int, can interpret failure decent indicator not number - hence catching valueerror exception.

your other use of exceptions unnecessary.

the try-except construct used handling exceptions modules can throw. should never used alternative if-else.

also, don't need run through every element of list find match, use in operator.

if ind in value:     # stuff 

Popular posts from this blog

php - How should I create my API for mobile applications (Needs Authentication) -

5 Reasons to Blog Anonymously (and 5 Reasons Not To)

Google AdWords and AdSense - A Dynamic Small Business Marketing Duo