feedthemachine feedthemachine -4 years ago 35
Python Question

python `else` doesn't work as expected

def greet(language):
database = {'english': 'Welcome',
'czech': 'Vitejte',
'danish': 'Velkomst',
'welsh': 'Croeso'}
for k, v in database.items():
if language == k:
return v
# else: return('Welcome')

print(greet('czech'))
> Vitejte


If I uncomment
else: return('Welcome')
(so if the greeting language is not in the list) I expect to receive 'Welcome' but it returns 'Welcome' no matter if I enter the existing or non-existing language.

I had also tried
elif language =!= k
but it appeared to work in the same unwanted fashion

Answer Source

You want this instead:

def greet(language):
    database = {'english': 'Welcome',
                'czech': 'Vitejte',
                'danish': 'Velkomst',
                'welsh': 'Croeso'}
    for k, v in database.items():
        if language == k:
            return v

    # Return this only if none of the items matched.
    return('Welcome')

As your code currently stands, it only ever checks the first item in the dictionary. If that key matches, it returns the appropriate value. Otherwise, it returns "Welcome," but it never moves on to the second item.

In my code, it checks all of the items and returns the right value as soon as it finds a match. Only if it fails to find a match does it return "Welcome."

Incidentally, this is an even simpler version of the code:

def greet(language):
    database = {'english': 'Welcome',
                'czech': 'Vitejte',
                'danish': 'Velkomst',
                'welsh': 'Croeso'}
    return database.get(language, 'Welcome')

dict.get lets you do a dictionary lookup and use a default value if the item is not found.

It's basically short-hand for this (but dict.get is preferred):

if language in database:
    return database[language]
else:
    return 'Welcome'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download