在函数中同时返回布尔值和变量? Python
Returning a Boolean and a variable at same time in a function ? Python
是否可以 return 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
是的,您需要从返回的结果中解压这两个值:
i = 0
for i in range (0,10):
cond, y = foo(i)
if cond:
ref_value = y
是的,你上面的代码 returns a tuple
,你可以 return 多个这样的值(在元组或列表等中),但你必须接受它们 (unpack) 也都在调用方(要么全部接受它们,要么接受 tuple/list 作为单个元素)。 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'>
是否可以 return 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
是的,您需要从返回的结果中解压这两个值:
i = 0
for i in range (0,10):
cond, y = foo(i)
if cond:
ref_value = y
是的,你上面的代码 returns a tuple
,你可以 return 多个这样的值(在元组或列表等中),但你必须接受它们 (unpack) 也都在调用方(要么全部接受它们,要么接受 tuple/list 作为单个元素)。 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'>