Python的return语句用于从函数中返回值。我们只能在函数中使用return语句,不能在Python函数外部使用。
没有return语句的Python函数
Python中的每个函数都会返回某个值。如果函数没有return语句,则返回None
。
def print_something(s):
print('Printing::', s)
output = print_something('Hi')
print(f'A function without return statement returns {output}')
输出:

Python Return语句示例
我们可以在函数中执行一些操作,并使用return语句将结果返回给调用者。
def add(x, y):
result = x + y
return result
output = add(5, 4)
print(f'Output of add(5, 4) function is {output}')
输出:

带有表达式的Python return语句
在return语句中也可以包含表达式。在这种情况下,将计算表达式并返回结果。
def add(x, y):
return x + y
output = add(5, 4)
print(f'Output of add(5, 4) function is {output}')
输出:

Python 返回布尔值
让我们看一个例子,我们将返回函数参数的布尔值。我们将使用bool()函数获取对象的布尔值。
def bool_value(x):
return bool(x)
print(f'Boolean value returned by bool_value(False) is {bool_value(False)}')
print(f'Boolean value returned by bool_value(True) is {bool_value(True)}')
print(f'Boolean value returned by bool_value("Python") is {bool_value("Python")}')
输出:

Python 返回字符串
让我们看一个例子,我们的函数将返回参数的字符串表示形式。我们可以使用str()函数获取对象的字符串表示形式。
def str_value(s):
return str(s)
print(f'String value returned by str_value(False) is {str_value(False)}')
print(f'String value returned by str_value(True) is {str_value(True)}')
print(f'String value returned by str_value(10) is {str_value(10)}')
输出:

Python 返回元组
有时我们想将多个变量转换为元组。让我们看看如何编写一个从可变数量参数返回元组的函数。
def create_tuple(*args):
my_list = []
for arg in args:
my_list.append(arg * 10)
return tuple(my_list)
t = create_tuple(1, 2, 3)
print(f'Tuple returned by create_tuple(1,2,3) is {t}')
输出:

进一步阅读: Python *args 和 **kwargs
Python 函数返回另一个函数
我们也可以从返回语句中返回一个函数。这类似于柯里化,它是将接受多个参数的函数的评估转换为评估一系列具有单个参数的函数的技术。
def get_cuboid_volume(h):
def volume(l, b):
return l * b * h
return volume
volume_height_10 = get_cuboid_volume(10)
cuboid_volume = volume_height_10(5, 4)
print(f'Cuboid(5, 4, 10) volume is {cuboid_volume}')
cuboid_volume = volume_height_10(2, 4)
print(f'Cuboid(2, 4, 10) volume is {cuboid_volume}')
输出:

Python 函数返回外部函数
我们还可以返回一个在返回语句外定义的函数。
def outer(x):
return x * 10
def my_func():
return outer
output_function = my_func()
print(type(output_function))
output = output_function(5)
print(f'Output is {output}')
输出:

Python 返回多个值
如果您想从函数中返回多个值,您可以根据需要返回元组、列表或字典对象。但是,如果您必须返回大量值,那么使用序列会占用太多资源。在这种情况下,我们可以使用yield逐个返回多个值。
def multiply_by_five(*args):
for arg in args:
yield arg * 5
a = multiply_by_five(4, 5, 6, 8)
print(a)
# 显示值
for i in a:
print(i)
输出:

总结
Python的return语句用于从函数中返回输出。我们学到了我们也可以从另一个函数返回函数。此外,表达式会被评估,然后从函数中返回结果。
您可以从我们的GitHub存储库查看完整的Python脚本和更多Python示例。
Source:
https://www.digitalocean.com/community/tutorials/python-return-statement