16 python
让我们说我定义一个简单的函数,它将显示传递给它的整数:
def funct1(param1):
print(param1)
return(param1)
Run Code Online (Sandbox Code Playgroud)
输出将是相同的,但我知道当return在函数中使用语句时,可以再次使用输出.否则,print不能使用语句的值.但我知道这不是正式的定义,任何人都能为我提供一个好的定义吗?
wkl*_*wkl 26
完全不同的东西.想象一下,如果我有这个python程序:
#!/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()
Run Code Online (Sandbox Code Playgroud)
你期望什么是输出?
hello
hello
ret is : hello
other is: None
Run Code Online (Sandbox Code Playgroud)
为什么?因为print接受它的参数/表达式并将它们转储到标准输出,所以在我编写的函数中,print将输出值x,即hello.
printAndReturn将返回x方法的调用者,因此:
ret = printAndReturn()
ret将具有相同的价值x,即"hello"
printAndReturnNothing 没有返回任何东西,所以:
other = printAndReturnNothing()
other实际上None因为这是python函数的默认返回.Python函数总是返回一些东西,但如果没有return声明,函数将返回None.
通过python教程将向您介绍这些概念:http://docs.python.org/tutorial
以下是python教程中的函数:http://docs.python.org/tutorial/controlflow.html#defining-functions
像往常一样,这个例子演示了一些新的Python特性:
return语句返回一个函数的值.不带表达式参数的return返回None.从函数末尾掉落也会返回None.
随着print()您将显示到标准输出的值param1,而return您将发送param1给调用者.
这两个语句具有非常不同的含义,您不应该看到相同的行为.发布您的整个程序,更容易指出与您的区别.
编辑:正如其他人所指出的,如果你在交互式python shell中,你会看到相同的效果(打印的值),但这是因为shell评估表达式并打印它们的输出.
在这种情况下,具有return语句的函数被计算为其return自身的参数,因此回显返回值.不要让交互式shell欺骗你!:)
简单的例子来展示差异:
def foo():
print (5)
def bar():
return 7
x = foo()
y = bar()
print (x)
# will show "None" because foo() does not return a value
print (y)
# will show "7" because "7" was output from the bar() function by the return statement.
Run Code Online (Sandbox Code Playgroud)
小智 5
我将从基本解释开始。print只是向人类用户显示一个表示计算机内部正在发生的事情的字符串。计算机无法使用该打印。return是函数返回值的方式。该值通常是人类用户看不到的,但计算机可以在其他功能中使用它。
更广泛地说,打印不会以任何方式影响功能。它只是为了人类用户的利益而存在。它对于理解程序如何工作非常有用,并且可以在调试中用于在不中断程序的情况下检查程序中的各种值。
return是函数返回值的主要方式。所有函数都会返回一个值,如果没有 return 语句(或yield,但不用担心),它将返回None。然后,函数返回的值可以进一步用作传递给另一个函数的参数、存储为变量,或者只是为了人类用户的利益而打印。
考虑这两个程序:
def function_that_prints():
print "I printed"
def function_that_returns():
return "I returned"
f1 = function_that_prints()
f2 = function_that_returns()
print "Now let us see what the values of f1 and f2 are"
print f1
print f2
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
67052 次 |
| 最近记录: |