return 语句的目的是什么?它与印刷有什么不同?
return
语句有什么作用?在Python中应该如何使用呢?
return
与 print
有何不同?
另请参见
人们通常会尝试在函数内部的循环中使用 print
来查看多个值,并希望能够使用外部的结果。它们需要被返回,但是 return
第一次会退出该函数。请参阅如何使用“return”从循环中获取多个值?我可以将它们放入列表中吗?。
通常,初学者会编写一个最终打印
内容而不是返回
的函数它,然后还尝试打印
结果,导致意外的None
。请参阅为什么在我的函数输出后打印“None”?。
偶尔在 3.x 中,人们尝试将 print
的结果分配给一个名称,或者在另一个表达式中使用它,例如 input(print('prompt:'))
。在 3.x 中,print
是一个函数,因此这不是语法错误,但它返回 None
而不是显示的内容。请参阅为什么打印函数返回 None?。
有时,人们会编写尝试的代码打印
递归调用的结果,而不是正确返回
它。就像仅仅调用该函数一样,这无法通过递归将值传播回来。请参阅为什么我的递归函数返回 None?。
考虑 如何从函数获取结果(输出)?我稍后如何使用结果?对于仅关于如何使用return
的问题,而不考虑打印
。
What does the return
statement do? How should it be used in Python?
How does return
differ from print
?
See also
Often, people try to use print
in a loop inside a function in order to see multiple values, and want to be able to use the results from outside. They need to be returned, but return
exits the function the first time. See How can I use `return` to get back multiple values from a loop? Can I put them in a list?.
Often, beginners will write a function that ultimately print
s something rather than return
ing it, and then also try to print
the result, resulting in an unexpected None
. See Why is "None" printed after my function's output?.
Occasionally in 3.x, people try to assign the result of print
to a name, or use it in another expression, like input(print('prompt:'))
. In 3.x, print
is a function, so this is not a syntax error, but it returns None
rather than what was displayed. See Why does the print function return None?.
Occasionally, people write code that tries to print
the result from a recursive call, rather than return
ing it properly. Just as if the function were merely called, this does not work to propagate the value back through the recursion. See Why does my recursive function return None?.
Consider How do I get a result (output) from a function? How can I use the result later? for questions that are simply about how to use return
, without considering print
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(15)
print()
函数在控制台中写入(即“打印”)一个字符串。return
语句使您的函数退出并向其调用者返回一个值。一般来说,函数的要点是接受输入并返回一些东西。当函数准备好向其调用者返回值时,使用 return 语句。例如,下面是一个同时使用
print()
和return
的函数:现在您可以运行调用 foo 的代码,如下所示:
如果您将其作为脚本运行(例如
.py
文件)而不是在 Python 解释器中,您将得到以下输出:我希望这能让它更清楚。解释器将返回值写入控制台,这样我就可以明白为什么有人会感到困惑。
下面是解释器的另一个示例,它演示了这一点:
您可以看到,当从
bar()
调用foo()
时,1 不会写入控制台。相反,它用于计算从bar()
返回的值。print() 是一个会产生副作用的函数(它在控制台中写入一个字符串),但会继续执行下一条语句。
return
导致函数停止执行并将一个值传回给调用它的函数。The
print()
function writes, i.e., "prints", a string in the console. Thereturn
statement causes your function to exit and hand back a value to its caller. The point of functions in general is to take in inputs and return something. Thereturn
statement is used when a function is ready to return a value to its caller.For example, here's a function utilizing both
print()
andreturn
:Now you can run code that calls foo, like so:
If you run this as a script (e.g. a
.py
file) as opposed to in the Python interpreter, you will get the following output:I hope this makes it clearer. The interpreter writes return values to the console so I can see why somebody could be confused.
Here's another example from the interpreter that demonstrates that:
You can see that when
foo()
is called frombar()
, 1 isn't written to the console. Instead it is used to calculate the value returned frombar()
.print()
is a function that causes a side effect (it writes a string in the console), but execution resumes with the next statement.return
causes the function to stop executing and hand a value back to whatever called it.将 print 语句视为导致副作用,它使您的函数向用户写入一些文本,但它不能被其他函数使用函数。
我将尝试通过一些示例以及维基百科中的几个定义来更好地解释这一点。
这是维基百科中函数的定义
在数学中,函数将一个量(函数的参数,也称为输入)与另一个量(函数的值,也称为输出)相关联。 .
想一想。当你说函数有值时是什么意思?
这意味着您实际上可以用正常值替换函数的值! (假设这两个值是相同类型的值)
您为什么要问?
其他可以接受相同类型值作为输入的函数又如何呢?
对于仅依赖于输入来产生输出的函数,有一个奇特的数学术语:引用透明度。再次,来自维基百科的定义。
引用透明性和引用不透明性是计算机程序各部分的属性。如果一个表达式可以被其值替换而不改变程序的行为,则称该表达式是引用透明的。
如果您刚接触编程,可能有点难以理解这意味着什么,但我认为经过一些实验你就会得到它。
但一般来说,您可以在函数中执行诸如 print 之类的操作,并且还可以在末尾添加 return 语句。
请记住,当您使用 return 时,您基本上是在说“调用此函数与写入返回的值相同”,
如果您拒绝输入自己的返回值,Python 实际上会为您插入一个返回值,这称为“无” ",这是一种特殊类型,没有任何意义,或者为 null。
Think of the print statement as causing a side-effect, it makes your function write some text out to the user, but it can't be used by another function.
I'll attempt to explain this better with some examples, and a couple definitions from Wikipedia.
Here is the definition of a function from Wikipedia
A function, in mathematics, associates one quantity, the argument of the function, also known as the input, with another quantity, the value of the function, also known as the output..
Think about that for a second. What does it mean when you say the function has a value?
What it means is that you can actually substitute the value of a function with a normal value! (Assuming the two values are the same type of value)
Why would you want that you ask?
What about other functions that may accept the same type of value as an input?
There is a fancy mathematical term for functions that only depend on their inputs to produce their outputs: Referential Transparency. Again, a definition from Wikipedia.
Referential transparency and referential opaqueness are properties of parts of computer programs. An expression is said to be referentially transparent if it can be replaced with its value without changing the behavior of a program
It might be a bit hard to grasp what this means if you're just new to programming, but I think you will get it after some experimentation.
In general though, you can do things like print in a function, and you can also have a return statement at the end.
Just remember that when you use return you are basically saying "A call to this function is the same as writing the value that gets returned"
Python will actually insert a return value for you if you decline to put in your own, it's called "None", and it's a special type that simply means nothing, or null.
我认为字典是你最好的参考
Return和打印
简而言之:
返回返回一些东西或回复给调用者打印时的功能生成文本
I think the dictionary is your best reference here
Return and Print
In short:
return gives something back or replies to the caller of the function while print produces text
在 python 中,我们以
def
开始定义函数,并且通常(但不一定)以return
结束函数。假设我们需要一个将
2
添加到输入值x
的函数。在数学中,我们可能会写出类似f(x) = x + 2
的内容来描述这种关系:在x
处计算的函数值等于>x + 2
。在 Python 中,它看起来像这样: 也就是说
:我们
定义
ine一个名为f
的函数,它将被赋予一个x
值。当代码运行时,我们计算出x + 2
,并返回
该值。我们不是描述关系,而是列出计算结果必须采取的步骤。定义函数后,可以使用您喜欢的任何参数来调用它。它不必在调用代码中命名为
x
,甚至不必是变量:我们可以用其他方式编写该函数的代码。例如:
或者甚至
再次,我们按顺序执行步骤 -
x = x + 2
更改x
所指的内容(现在它意味着总和的结果),这就是通过return x
得到return
的内容(因为这是 *在return
发生时的值)。In python, we start defining a function with
def
, and generally - but not necessarily - end the function withreturn
.Suppose we want a function that adds
2
to the input valuex
. In mathematics, we might write something likef(x) = x + 2
, describing that relationship: the value of the function, evaluated atx
, is equal tox + 2
.In Python, it looks like this instead:
That is: we
def
ine a function namedf
, which will be given anx
value. When the code runs we figure outx + 2
, andreturn
that value. Instead of describing a relationship, we lay out steps that must be taken to calculate the result.After defining the function, it can be called with whatever argument you like. It doesn't have to be named
x
in the calling code, and it doesn't even have to be a variable:We could write the code for the function in some other ways. For example:
or even
Again, we are following steps in order -
x = x + 2
changes whatx
refers to (now it means the result from the sum), and that is what getsreturn
ed byreturn x
(because that's the value *at the time that thereturn
happens).return
表示“从该函数输出该值”。print
表示“将此值发送到(通常)stdout”在 Python REPL 中,默认情况下函数的返回值将输出到屏幕(这与
print
不同)编码>它)。此输出仅发生在 REPL 上,不会在从.py
文件运行代码时发生。它与 REPL 中任何其他表达式的输出相同。这是打印的示例:
这是返回的示例:
return
means "output this value from this function".print
means "send this value to (generally) stdout"In the Python REPL, a function's return value will be output to the screen by default (this isn't the same as
print
ing it). This output only happens at the REPL, not when running code from a.py
file. It is the same as the output from any other expression at the REPL.This is an example of print:
This is an example of return:
此答案涵盖了上面未讨论的一些情况。
return 语句允许您在到达末尾之前终止函数的执行。这会导致执行流程立即返回到调用者。
第 4 行:
条件语句执行后,
ret()
函数由于return temp
而终止(第 4 行)。因此
print("return statements")
不会被执行。输出:
出现在条件语句之后或控制流无法到达的地方的代码是死代码。
返回值
在第 4 行和第 8 行中,return 语句用于在条件执行后返回临时变量的值。
要显示 print 和 return 之间的区别:
输出:
This answer goes over some of the cases that have not been discussed above.
The return statement allows you to terminate the execution of a function before you reach the end. This causes the flow of execution to immediately return to the caller.
In line number 4:
After the conditional statement gets executed the
ret()
function gets terminated due toreturn temp
(line 4).Thus the
print("return statement")
does not get executed.Output:
This code that appears after the conditional statements, or the place the flow of control cannot reach, is the dead code.
Returning Values
In lines number 4 and 8, the return statement is being used to return the value of a temporary variable after the condition has been executed.
To bring out the difference between print and return:
Output:
请注意,
return
也可用于控制流。通过在函数中间放置一个或多个return
语句,我们可以说:“停止执行该函数。我们要么得到了我们想要的结果,要么出了问题!”例如,想象一下尝试实现
str.find(sub)
如果我们只有str.index(sub)
可用(如果未找到子字符串,index
会引发ValueError
,而 <代码>查找返回<代码>-1)。我们可以使用
try/ except
块:这很好,而且可以工作,但表达能力不太好。目前尚不清楚什么会导致
str.index
引发ValueError
:此代码的读者必须了解str.index
的工作原理为了理解find
的逻辑。我们可以创建代码文档本身,而不是添加文档字符串,说“...除非找不到
sub
,在这种情况下返回-1
”,像这样:这样逻辑就很清晰了。
另一个好处是,一旦我们返回 s.index(sub) ,我们就不需要将其包装在
try/ except
中,因为 我们已经知道子字符串存在!请参阅
Note that
return
can also be used for control flow. By putting one or morereturn
statements in the middle of a function, we can say: "stop executing this function. We've either got what we wanted or something's gone wrong!"For example, imagine trying to implement
str.find(sub)
if we only hadstr.index(sub)
available (index
raises aValueError
if the substring isn't found, whereasfind
returns-1
).We could use a
try/except
block:This is fine, and it works, but it's not very expressive. It's not immediately clear what would cause
str.index
to raise aValueError
: a reader of this code must understand the workings ofstr.index
in order to understand the logic offind
.Rather than add a doc-string, saying "...unless
sub
isn't found, in which case return-1
", we could make the code document itself, like this:This makes the logic very clear.
The other nice thing about this is that once we get to
return s.index(sub)
we don't need to wrap it in atry/except
because we already know that the substring is present!See the Code Style section of the Python Guide for more advice on this way of using
return
.尽可能简单地说:
return
使值(通常是一个变量)可供调用者使用(例如,由使用return< 的函数存储) /code> 位于内)。如果没有
return
,您的值或变量将无法供调用者存储/重用。相比之下,
print
会打印到屏幕上,但不会使值或变量可供调用者使用。To put it as simply as possible:
return
makes the value (a variable, often) available for use by the caller (for example, to be stored by a function that the function usingreturn
is within). Withoutreturn
, your value or variable wouldn't be available for the caller to store/re-use.print
, by contrast, prints to the screen - but does not make the value or variable available for use by the caller.“return”和“print”之间的区别还可以在以下示例中找到:
RETURN:
上面的代码将为所有输入提供正确的结果。
打印:
注意:这对于许多测试用例来说都会失败。
错误:
FAILURE
:测试用例输入:3、8。
FAILURE
: 测试用例输入: 4, 3.
FAILURE
: 测试用例输入: 3, 3.
您通过了 3 项测试中的 0 项案例
Difference between "return" and "print" can also be found in the following example:
RETURN:
The above code will give correct results for all inputs.
PRINT:
NOTE: This will fail for many test cases.
ERROR:
FAILURE
: Test case input: 3, 8.
FAILURE
: Test case input: 4, 3.
FAILURE
: Test case input: 3, 3.
You passed 0 out of 3 test cases
这是我的理解。 (希望它能帮助某人并且它是正确的)。
所以这段简单的代码可以计算某事出现的次数。回报的安置意义重大。它告诉你的程序哪里需要这个值。因此,当您打印时,您将输出发送到屏幕。当你返回时,你告诉这个值去某个地方。在本例中,您可以看到 count = 0 与 return 缩进 - 我们希望值 (count + 1) 替换 0。
如果您在进一步缩进 return 命令时尝试遵循代码逻辑,则输出将始终为 1,因为我们永远不会告诉初始计数发生变化。
我希望我做对了。
哦,return 总是在函数内部。
Here is my understanding. (hope it will help someone and it's correct).
So this simple piece of code counts number of occurrences of something. The placement of return is significant. It tells your program where do you need the value. So when you print, you send output to the screen. When you return you tell the value to go somewhere. In this case you can see that count = 0 is indented with return - we want the value (count + 1) to replace 0.
If you try to follow logic of the code when you indent the return command further the output will always be 1, because we would never tell the initial count to change.
I hope I got it right.
Oh, and return is always inside a function.
return
应该用于递归函数/方法,或者您希望将返回值用于算法中的后续应用程序。当您想要向用户显示有意义且所需的输出,并且不想让用户不感兴趣的中间结果弄乱屏幕时,应该使用 print ,尽管它们对调试你的代码。
以下代码展示了如何正确使用
return
和print
:此解释适用于所有编程语言,而不仅仅是 python。
return
should be used for recursive functions/methods or you want to use the returned value for later applications in your algorithm.print
should be used when you want to display a meaningful and desired output to the user and you don't want to clutter the screen with intermediate results that the user is not interested in, although they are helpful for debugging your code.The following code shows how to use
return
andprint
properly:This explanation is true for all of the programming languages not just python.
return
是函数定义的一部分,而print
将文本输出到标准输出(通常是控制台)。函数是接受参数并返回值的过程。
return
用于后者,而前者则用def
完成。例子:
return
is part of a function definition, whileprint
outputs text to the standard output (usually the console).A function is a procedure accepting parameters and returning a value.
return
is for the latter, while the former is done withdef
.Example:
return
函数最好的一点是你可以从函数返回一个值,但你可以使用print
做同样的事情,那么有什么区别呢?基本上
return
不仅仅是返回,它以对象形式提供输出,以便我们可以将函数的返回值保存到任何变量,但我们不能使用print
因为它是相同的就像C 编程
中的stdout/cout
一样。按照下面的代码可以更好地理解
代码
我们现在正在为
加、减、乘、
和除
编写我们自己的数学函数。需要注意的重要一点是最后一行我们说 returna + b
(在add
中)。其作用如下:a
和b
。a
和b
,然后返回它们。”a + b
结果分配给变量。Best thing about
return
function is you can return a value from function but you can do same withprint
so whats the difference ?Basically
return
not about just returning it gives output in object form so that we can save that return value from function to any variable but we can't do withprint
because its same likestdout/cout
inC Programming
.Follow below code for better understanding
CODE
We are now doing our own math functions for
add, subtract, multiply,
anddivide
. The important thing to notice is the last line where we say returna + b
(inadd
). What this does is the following:a
andb
.a + b
. You might say this as, "I adda
andb
then return them."a + b
result to a variable.简单的事实是,
print
和return
彼此无关。print
用于在终端中显示内容(对于命令行程序)。1return
用于当您调用函数时返回结果,以便您可以在程序逻辑的下一步中使用它。许多初学者在 Python 的解释器提示中尝试代码时会感到困惑2,如
值被显示;这不是意味着
return
显示内容吗? 不。如果您在.py
文件中尝试相同的代码,您可以亲眼看到运行该脚本不会导致显示1
。这个实际上不应该令人困惑,因为它的工作方式与任何其他表达式相同:
这会显示在交互式提示符处,但如果我们制作一个仅显示
1 + 1< 的脚本,则不会出现这种情况。 /code> 并尝试运行它。
再次强调:如果您需要将某些内容作为脚本的一部分显示,请
打印
它。如果您需要在下一步计算中使用它,请返回
它。秘密在于交互式提示导致显示结果,不是代码。这是提示为您执行的单独步骤,以便您可以一次查看代码如何工作,以进行测试。
现在,让我们看看
print
会发生什么:无论我们是在交互式提示中还是在脚本中,都会显示结果。
print
明确用于显示值 - 正如我们所看到的,它的显示方式有所不同。交互式提示使用从example
返回的值的repr
,而print
使用值的str
。实际上:
print
以文本形式向我们展示了值的样子(对于字符串,这仅表示字符串的内容)。交互式提示向我们显示值是什么 - 通常,通过编写类似于我们将使用的源代码来创建它的内容。3但是等等 -
print
是一个函数,对吧? (无论如何,在 3.x 中)。所以它返回了一个值,对吗?解释器提示符不是应该在单独的步骤中显示它吗?发生了什么?还有一个技巧:
print
返回 特殊值None
,解释器提示将忽略它。我们可以通过使用一些计算结果为 None 的表达式来测试这一点:在每种情况下,根本没有单独的行用于输出,甚至没有空行 - 解释器提示符只是返回到提示符。
1它也可以用来写入文件,尽管这是一个不太常见的想法,但通常使用
.write
方法会更清晰。2 这有时称为 REPL,代表“读取-评估-打印循环”。
3 这并不总是实用,甚至不可能 - 特别是当我们开始定义自己的类时。严格的规则是
repr
将依靠对象的.__repr__
方法来完成脏工作;同样,str
依赖于.__str__
。4 Python 中的函数 隐式返回
None
如果它们没有显式返回值。The simple truth is that
print
andreturn
have nothing to do with each other.print
is used to display things in the terminal (for command-line programs).1return
is used to get a result back when you call a function, so that you can use it in the next step of the program's logic.Many beginners are confused when they try out code at Python's interpreter prompt2, like
The value was displayed; doesn't this mean that
return
displays things? No. If you try the same code in a.py
file, you can see for yourself that running the script doesn't cause the1
to display.This shouldn't actually be confusing, because it works the same way as any other expression:
This displays at the interactive prompt, but not if we make a script that just says
1 + 1
and try running it.Again: if you need something to display as part of your script,
print
it. If you need to use it in the next step of the calculation,return
it.The secret is that the interactive prompt is causing the result to be displayed, not the code. It's a separate step that the prompt does for you, so that you can see how the code works a step at a time, for testing purposes.
Now, let's see what happens with
print
:The result will display, whether we have this in an interactive prompt or in a script.
print
is explicitly used to display the value - and as we can see, it displays differently. The interactive prompt uses what is called therepr
of the value that was returned fromexample
, whileprint
uses thestr
of the value.In practical terms:
print
shows us what the value looks like, in text form (for a string, that just means the contents of the string as-is). The interactive prompt shows us what the value is - typically, by writing something that looks like the source code we would use to create it.3But wait -
print
is a function, right? (In 3.x, anyway). So it returned a value, right? Isn't the interpreter prompt supposed to display that in its separate step? What happened?There is one more trick:
print
returns the special valueNone
, which the interpreter prompt will ignore. We can test this by using some expressions that evaluate to None:In each case, there is no separate line at all for output, not even a blank line - the interpreter prompt just goes back to the prompt.
1 It can also be used to write into files, although this is a less common idea and normally it will be clearer to use the
.write
method.2 This is sometimes called the REPL, which stands for "read-eval-print loop".
3 This isn't always practical, or even possible - especially once we start defining our own classes. The firm rule is that
repr
will lean on the.__repr__
method of the object to do the dirty work; similarly,str
leans on.__str__
.4 Functions in Python implicitly return
None
if they don't explicitly return a value.Return 语句——将根据您的函数返回一些值。
如果你调用上面的函数并传递数字 5 那么它将返回 true,否则它将返回 false。
打印功能——它将打印您提供给打印功能或打印功能括号中的内容。
Return statement -- will return some values according your function.
if you call above function and you pass number 5 then it will return true else it will return false.
Printing function -- it will print content that you have given to the print function or with in print function bracket.