为什么这会返回国家代码?为什么当我不放入else语句时这段代码返回None,但是当我放入else语句时它不会返回None?
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')
为什么不能返回国家代码?
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')
主要区别在于我如何缩进“返回无”。即使我把else语句也不返回代码。有人可以向我解释这个吗?我是编程新手。
确实。但是,如果我使用else语句并将其放在for代码中,它仍会返回None。你能向我解释一下为什么? – Katrina
刚刚编辑了更详细的答案,但你必须得到缩进的东西 - 像这样的实验 - 才能完全理解它。 – TomServo