2017-06-04 45 views
1

为什么这会返回国家代码?为什么当我不放入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语句也不返回代码。有人可以向我解释这个吗?我是编程新手。

回答

0

缩进的区别 - 仔细检查缩进。在第二个示例中,return none位于INSIDE for code循环中。因此,只要`name == country_name'失败一次,它就会返回None。

Python缩进在基于C语言或BASIC方言中的Begin-End中使用大括号。这是Python的主要特质。

+0

确实。但是,如果我使用else语句并将其放在for代码中,它仍会返回None。你能向我解释一下为什么? – Katrina

+0

刚刚编辑了更详细的答案,但你必须得到缩进的东西 - 像这样的实验 - 才能完全理解它。 – TomServo

0

好的JLH是正确的。在第二组代码中:由于else在for循环中,列表中的第一个名字将触发else代码(除非您正在寻找列表中的第一个),它将不返回任何值。因此,除非第一个元素是您正在查找的元素,否则它将始终返回None。

相关问题