[英]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.