Ex48 - try/except not working

lexicon = {
        'north': 'direction',
        'south': 'direction',
        'east': 'direction',
        'west': 'direction',
        'go': 'verb',
        'kill': 'verb',
        'eat': 'verb',
        'the': 'stop',
        'in': 'stop',
        'of': 'stop',
        'bear': 'noun',
        'princess': 'noun',
        1234: 'number'
        }

def scan(sentence):
    results = []
    words = sentence.split()
    
    for word in words:
        word_type = lexicon.get(word)
        results.append((word_type, word))
        
        try:
            number = int(word)
        except ValueError:
            pass
    return results

So i am getting AssertionError: Lists differ: [(None, ‘1234’)] != [(‘number’, 1234)] when running this. I don’t quite understand how to implement the try and except into the for loop. Any ideas?

So, it’s time to debug this then. You need to print out what you’re actually getting from the lexicon when you call lexicon.get.

Also, remember to do this to your code when you paste it here:

[code]
# my pythons
[/code]

I did it for you but when you post a followup wrap your code our output with that and it’ll show up nice.

Hello @MilanM.

I made my loop look for any match in the wordtypes (direction, noun, verb or stop).

for word in sentence:
    if word in lexicon:... # correction. sentence was wrong

If there was no match at all I tested if it was a integer.
For this I made a function

def test_if_number(s):
    try:
        return int(s)
    except ValueError:
        return None

Then I could call for this function in the elif part of my loop.

 elif word not in lexicon:
            number = test_if_number(word)
            if number:
                ...

When I did like this I match any number at all.
If it was’nt a number and not in lexicon( all other words in any language) it was an ‘error’

2 Likes