[英]differences between return and print in a function
Can anyone explain why we get different output using print and return?谁能解释为什么我们使用打印和返回得到不同的输出?
For this code:对于此代码:
def string(txt):
for char in txt:
print(char)
string('Stack')
the output would be:输出将是:
S
t
a
c
k
And for this code:对于此代码:
def string1(txt):
for char in txt:
return char
string1('Stack')
the output would be:输出将是:
'S'
当您使用 return 函数停止并返回一个值时,它会跳出循环
As soon as you use return you would return the value and leave the function.一旦你使用 return 你就会返回值并离开函数。
def string(txt):
for char in txt:
print(char)
return
string('Stack')
This code would also only print an "S" as your example with return.此代码也只会打印“S”作为您的返回示例。 Because return as the word say return to the position you called it.因为返回这个词说返回到你调用它的位置。
Both functions iterate through the characters of the txt
parameter, but the first one, string
uses the return
statements, which breaks the iteration and returns the first character to the caller.两个函数都遍历txt
参数的字符,但第一个string
使用了return
语句,这会中断迭代并将第一个字符返回给调用者。 This is why you see only the S
of Stack
这就是为什么你只看到Stack
的S
print
on the other hand outputs all the characters in order to the standard output , and returns only after the loop is finished.另一方面, print
将所有字符按顺序输出到标准输出,并仅在循环完成后返回。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.