为什么这段代码在我不放else语句的时候是returnNone,而当我放else语句的时候却没有returnNone?

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?

为什么这个 return 国家代码?

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') 

为什么这个 return 没有国家代码?

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') 

主要区别在于我如何缩进 'return None.' 即使我放置了 else 语句它也没有 return 代码。有人可以向我解释一下吗?我是编程新手。

缩进 的区别 -- 仔细检查您的缩进。在第二个例子中,return nonefor code 循环中。所以它 returns None 一旦 `if name == country_name' 失败一次。

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

好的,JLH 是正确的。在第二组代码中:由于 else 在 for 循环中,列表中的第一个名称将触发 else 代码(除非您正在寻找列表中的第一个 1),它将 return none.因此,除非第一个元素是您要查找的元素,否则它将始终 return None.