Katrina
Katrina

Reputation: 109

Why does this code return None when I don't put the else statement, but it doesn't return None when I put the else statement?

Why does this return the country codes?

from pygal.maps.world import COUNTRIES 

def get_country_code(country_name): 
    """Return the Pygal 2-digit country code for the given country."""
    for code, name in COUNTRIES.items(): 
        if name == country_name:
            return code 
    return None 

print(get_country_code('Andorra'))
print(get_country_code('United Arab Emirates') 

Why doesn't this return the country codes?

from pygal.maps.world import COUNTRIES 

def get_country_code(country_name): 
    """Return the Pygal 2-digit country code for the given country."""
    for code, name in COUNTRIES.items(): 
        if name == country_name:
            return code 
        return None 

print(get_country_code('Andorra'))
print(get_country_code('United Arab Emirates') 

The main difference is how I indented the 'return None.' Even if I put the else statement it doesn't return the codes. Can someone please explain this to me? I'm new in programming.

Upvotes: -1

Views: 116

Answers (2)

rjp
rjp

Reputation: 1

Ok JLH is correct. In the second set of code: Since the else is in the for loop the first name in the list will trigger the else code (unless you are looking for the first 1 on the list) which will return none. So unless the first element is the one you are looking for it will always return None.

Upvotes: 0

TomServo
TomServo

Reputation: 7409

The indentation is the difference -- check your indentation closely. in the second example, the return none is INSIDE the for code loop. So it returns None as soon as `if name == country_name' fails once.

Python indentation acts like braces in C-based languages or Begin-End in BASIC dialects. It's the main idiosyncrasy of Python.

Upvotes: 0

Related Questions