返回vs打印列表 [英] return vs print list

查看:65
本文介绍了返回vs打印列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Very new to programming.
Wondering why does this example print all the items in the list, while the second example prints only the first?

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

n = [4, 5, 7]
list_function(n)


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

n = [4, 5, 7]
print list_function(n)

推荐答案

第一个示例遍历x中的每个项目,并将每个项目打印到屏幕上.您的第二个示例开始遍历x中的每个项目,但随后返回第一个,从而在该点结束函数的执行.

Your first example iterates through each item in x, printing each item to the screen. Your second example begins iterating through each item in x, but then it returns the first one, which ends the execution of the function at that point.

让我们仔细看一下第一个示例:

Let's take a closer look at the first example:

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)

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

Inside the function, the for loop will begin iterating over x. First y is set to 4, which is printed. Then it's set to 5 and printed, then 7 and printed.

现在来看第二个例子:

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

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

Inside the function, the for loop will begin iterating over x. First y is set to 4, which is then returned. At this point, execution of the function is halted and the value is returned to the caller. y is never set to 5 or 7. The only reason this code still does print something to the screen is because it's called on the line print list_function(n), so the return value will be printed. If you just called it with list_function(n) as in the first example, nothing would be printed to the screen.

这篇关于返回vs打印列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆