是否可以从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

最佳答案

是的,您的上面的代码返回了tuple,您可以返回多个类似的值(在元组或列表等中),但是您还必须在调用方全部接受(解压)它们(接受它们)全部,或接受元组/列表作为单个元素)。示例/演示-

>>> 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'>

关于python - 在函数中同时返回 bool 值和变量? python ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31859014/

10-12 17:23
查看更多