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.
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.