返回vs打印列表

Dud*_*ude 5 python printing return list

编程很新.
想知道为什么这个例子打印列表中的所有项目,而第二个例子只打印第一个?

def list_function(x):
    for y in x:
        print y 

n = [4, 5, 7]
list_function(n)
Run Code Online (Sandbox Code Playgroud)
def list_function(x):
    for y in x:
        return y 

n = [4, 5, 7]
print list_function(n)
Run Code Online (Sandbox Code Playgroud)

Cyp*_*ase 6

您的第一个示例迭代 中的每个项目x,并将每个项目打印到屏幕上。您的第二个示例开始迭代 中的每个项目x,但随后返回第一个项目,从而在此时结束函数的执行。

让我们仔细看看第一个例子:

def list_function(x):
    for y in x:
        print(y)  # Prints y to the screen, then continues on

n = [4, 5, 7]
list_function(n)
Run Code Online (Sandbox Code Playgroud)

在函数内部,for循环将开始迭代x。首先y设置为4,并打印出来。然后将其设置为5并打印,然后7打印。

现在看第二个例子:

def list_function(x):
    for y in x:
        return y  # Returns y, ending the execution of the function

n = [4, 5, 7]
print(list_function(n))
Run Code Online (Sandbox Code Playgroud)

在函数内部,for循环将开始迭代x。首先y设置为4,然后返回。此时,函数的执行将停止,并将值返回给调用者。y永远不会设置为57。此代码仍然在屏幕上打印某些内容的唯一原因是因为它是在 line 上调用的print list_function(n),因此将打印返回值。如果您只是像第一个示例中那样调用它list_function(n),则屏幕上不会打印任何内容。