[英]Returning a Boolean and a variable at same time in a function ? Python
Is it possible to return a boolean and a variable from a function in python 是否可以从python中的函数返回布尔值和变量
def foo(self, x):
if x > 5:
y = 2 #for workaround with pass by reference method
return true , y
# calling it by
i = 0
for i in range (0,10):
if foo(i):
ref_value = y #to get the reference value
Yes, your above code returns a tuple
, you can return multiple values like that (in a tuple or a list, etc) , but you will have to accept them ( unpack ) all at the calling side as well (either accept them all, or accept the tuple/list as a single element). 是的,上面的代码返回一个tuple
,您可以返回多个类似的值(在元组或列表等中),但是您还必须在调用方全部接受它们( 解包 )(要么全部接受它们,或接受元组/列表作为单个元素)。 Example/Demo - 示例/演示-
>>> def foo(i):
... if i > 5:
... y = 2
... return True, y
... return False,0
...
>>> for i in range(0,10):
... x,y = foo(i)
... if x:
... ret_value = y
... else:
... ret_value = 0
... print(ret_value)
...
0
0
0
0
0
0
2
2
2
2
>>> type(foo(6)) #Example to show type of value returned.
<class 'tuple'>
Yes, you would need to unpack both values from the returned result: 是的,您需要从返回的结果中解压缩两个值:
i = 0
for i in range (0,10):
cond, y = foo(i)
if cond:
ref_value = y
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.