简体   繁体   English

为什么我在循环返回和打印时得到不同的结果?

[英]Why I am getting different results for returning versus printing in a loop?

def myarray(num_list):
    for item in num_list:
        return item

def myarray(num_list):
    for item in num_list:
        print (item)

When I run myarray([2,4,6]) the first returns only 2 while the second prints all the items:当我运行myarray([2,4,6]) ,第一个只返回2而第二个打印所有项目:

2
4
6

Why?为什么? What's the difference?有什么不同?

Please format your post so it shows the code correctly.请格式化您的帖子,以便正确显示代码。 You can edit the post.您可以编辑帖子。 Select the code part and press on the two curly brackets.选择代码部分并按下两个大括号。

The first statment only returns "2" because the keyword "return" stops the rest of the loop from running.第一个语句只返回“2”,因为关键字“return”会阻止循环的其余部分运行。

In the second version you simply print out the content of the list for each position in the list.在第二个版本中,您只需打印列表中每个位置的列表内容。 Thats why the second version shows all 3 numbers.这就是为什么第二个版本显示所有 3 个数字。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么在 while 循环和外部声明变量monthly_salary 时会得到不同的输出? - Why am I getting a different ouput when the variable monthly_salary is declared in the while loop versus outside? 为什么我使用不同的算法得到不同的引导结果? - Why am I getting different bootstrap results using different algorithms? 为什么对于类似的查询我有2个不同的结果? - Why am I getting 2 different results for similar queries? Python:为什么我得到不同的排序结果 - Python: Why am I getting different sorted results 打印相同的变量并将其附加到列表时,我得到了不同的值,这是为什么? - I am getting different value when printing and appending same variable to a list, Why is that? 为什么我没有得到 print 和 for 的任何结果? - Why am I not getting any results with print and for? 为什么使用多处理会得到如此糟糕的结果? - Why am I getting such bad results with multiprocessing? 为什么我使用相同的脚本得到结果? - Why am I getting results with the same script? 当我在Python控制台中运行此代码时,为什么会得到不同的结果? - Why I am getting different results when I run this code in my Python console? 装饰者:为什么我得到不同的结果? 如果我要传递带有参数的函数,@符号是强制性的吗? - Decorators: Why am I getting different results? If I'm passing a function with parameters, is @ notation compulsory?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM