BBe*_*dit 1 python return-value
我已经学习 Python 好几天了。但是,我不明白返回。我从我的教科书和网上阅读了一些解释;他们没有帮助!
也许有人可以用简单的方式解释 return 的作用?我写了几个有用的(对我来说)Python 脚本,但我从来没有用过 return因为我不知道它的作用。
你能提供一个简单的例子吗来说明为什么应该使用 return 吗?
它似乎也什么都不做:
def sqrt(n):
approx = n/2.0
better = (approx + n/approx)/2.0
while better != approx:
approx = better
better = (approx + n/approx)/2.0
return approx
sqrt(25)
Run Code Online (Sandbox Code Playgroud)
我的课本告诉我: “试着用 25 作为参数调用这个函数,以确认它返回 5.0。”
我知道如何检查的唯一方法是使用print。但我不知道这是否是他们正在寻找的。问题只是说用 25 调用。它没有说要在代码中添加更多内容以确认它返回 5.0。
return 从函数返回一个值:
def addseven(n):
return n + 7
a = 9
b = addseven(a)
print(b) # should be 16
Run Code Online (Sandbox Code Playgroud)
它还可以用于退出函数:
def addseventosix(n):
if n != 6:
return
else:
return n + 7
Run Code Online (Sandbox Code Playgroud)
但是,即使您return在函数中没有语句(或者您在没有指定要返回的值的情况下使用它),该函数仍然会返回 - None。
def functionthatisuseless(n):
n + 7
print(functionthatisuseless(8)) # should output None
Run Code Online (Sandbox Code Playgroud)
有时您可能希望从函数返回多个值。但是,您不能有多个return语句 - 控制流在第一个语句之后离开函数,因此它之后的任何内容都不会被执行。在Python中,我们通常使用元组,并且元组解包:
def addsevenandaddeight(n):
return (n+7, n+8) # the parentheses aren't necessary, they are just for clarity
seven, eight = addsevenandaddeight(0)
print(seven) # should be 7
print(eight) # should be 8
Run Code Online (Sandbox Code Playgroud)
return 语句允许您对其他函数的结果调用函数:
def addseven(n):
return n+7
def timeseight(n):
return n*8
print(addseven(timeseight(9))
# what the intepreter is doing (kind of):
# print(addseven(72)) # 72 is what is returned when timeseight is called on 9
# print(79)
# 79
Run Code Online (Sandbox Code Playgroud)