“打印"和“打印"之间的正式区别是什么?和“返回"? [英] What is the formal difference between "print" and "return"?
问题描述
假设我定义了一个简单的函数,它将显示传递给它的整数:
Lets say I define a simple function which will display an integer passed to it:
def funct1(param1):
print(param1)
return(param1)
输出将是相同的,但我知道当在函数中使用 return
语句时,输出可以再次使用.否则不能使用 print
语句的值.但我知道这不是正式的定义,谁能给我一个好的定义?
the output will be the same but and I know that when a return
statement is used in a function the output can be used again. Otherwise the value of a print
statement cannot be used. But I know this is not the formal definition, Can anyone provide me with a good definition?
推荐答案
截然不同的事情.想象一下,如果我有这个 python 程序:
Dramatically different things. Imagine if I have this python program:
#!/usr/bin/env python
def printAndReturnNothing():
x = "hello"
print(x)
def printAndReturn():
x = "hello"
print(x)
return x
def main():
ret = printAndReturn()
other = printAndReturnNothing()
print("ret is: %s" % ret)
print("other is: %s" % other)
if __name__ == "__main__":
main()
您希望输出什么?
hello
hello
ret is : hello
other is: None
<小时>
为什么?
为什么?因为 print
接受它的参数/表达式并将它们转储到标准输出,所以在我编写的函数中,print
将输出 x
的值,这是hello
.
Why?
Why? Because print
takes its arguments/expressions and dumps them to standard output, so in the functions I made up, print
will output the value of x
, which is hello
.
printAndReturn
会将x
返回给方法的调用者,所以:
printAndReturn
will returnx
to the caller of the method, so:
ret = printAndReturn()
ret
将与 x
具有相同的值,即 "hello"
ret
will have the same value as x
, i.e. "hello"
printAndReturnNothing
不返回任何内容,因此:
printAndReturnNothing
doesn't return anything, so:
other = printAndReturnNothing()
other
实际上变成了 None
因为这是 Python 函数的默认返回值.Python 函数总是返回一些东西,但如果没有声明 return
,函数将返回 None
.
other
actually becomes None
because that is the default return from a python function. Python functions always return something, but if no return
is declared, the function will return None
.
通过 Python 教程将向您介绍这些概念:http://docs.python.org/tutorial
Going through the python tutorial will introduce you to these concepts: http://docs.python.org/tutorial
以下是 Python 教程中有关函数的一些内容:http://docs.python.org/tutorial/controlflow.html#defining-functions
Here's something about functions form python's tutorial: http://docs.python.org/tutorial/controlflow.html#defining-functions
这个例子和往常一样,展示了一些新的 Python 特性:
This example, as usual, demonstrates some new Python features:
return 语句返回一个函数的值.没有表达式参数的 return 返回 None.从函数的末尾脱落也会返回 None.
The return statement returns with a value from a function. return without an expression argument returns None. Falling off the end of a function also returns None.
这篇关于“打印"和“打印"之间的正式区别是什么?和“返回"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!