return从函数返回值:
def addseven(n): return n + 7a = 9b = addseven(a)print(b) # should be 16
它也可以用于退出功能:
def addseventosix(n): if n != 6: return else: return n + 7
但是,即使您
return在函数中没有语句(或在不指定要返回值的情况下使用它),该函数仍会返回-
None。
def functionthatisuseless(n): n + 7print(functionthatisuseless(8)) # should output None
有时您可能想从一个函数返回多个值。但是,您不能有多个
return语句-
控制流会在第一个语句之后留下该函数,因此它执行后的所有操作都不会执行。在Python中,我们通常使用元组和元组解包:
def addsevenandaddeight(n): return (n+7, n+8) # the parentheses aren't necessary, they are just for clarityseven, eight = addsevenandaddeight(0)print(seven) # should be 7print(eight) # should be 8
return语句使您可以根据其他函数的结果调用函数:
def addseven(n): return n+7def timeseight(n): return n*8print(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



