简体   繁体   English

从内循环和外循环返回 return 之间有什么区别?

[英]what is difference between returning return from inside loop and outside loop?

Actually, I am a newbie in python.实际上,我是python的新手。 I have doubt in return in for loop section.我对 for 循环部分的回报有疑问。 -> if i return inside loop output is 1 for (for string "abcd"). -> 如果我返回内部循环输出为 1(对于字符串“abcd”)。 -> if I return with the same indentation that for is using in code, the output will 4. Can you please explain this happening? -> 如果我返回与代码中使用的相同的缩进,输出将为 4。你能解释一下这种情况吗?

I have added my problem briefly using the comment in code also.我还使用代码中的注释简要添加了我的问题。

def print_each_letter(word):
   counter = 0   
   for letter in word:
     counter += 1
     return counter      #its returning length 1  why ?
   return counter        # its returning length 4  why?

print_each_letter("abcd")

return退出函数,它返回4因为它在循环之外,并且循环完成了它的所有操作并加起来为4 (因为abcd的长度是 4)并返回值。

According to the python3 docs :根据 python3 文档

return leaves the current function call with the expression list (or None) as return value return 以表达式列表(或 None)作为返回值离开当前函数调用

The reason for the different return values is that the function exits when return is called at the end of the first iteration (hence the value of 1).返回值不同的原因是函数在第一次迭代结束时调用return时退出(因此值为 1)。

Because the return inside the loop executes the first time the loop is executed, so this happens:因为循环内部的return是第一次执行循环时执行的,所以会出现这种情况:

counter = 0
for letter in word:
    #'a'
    counter += 1
    return counter #return counter (1) and terminate function.

but if you let the loop run first:但是如果你让循环先运行:

counter = 0
for letter in word:
    #'a'
    counter += 1 #1
    #'b'
    counter += 1 #2
    #'c'
    counter += 1 #3
    #'d'
    counter += 1 #4
return counter #return counter (4) and terminate function.

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM