2017-06-04 31 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。

相關問題