1

Is it possible to return a boolean and a variable from a function in 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 
1
  • "for workaround with pass by reference method" - Python doesn't have pass by reference. y = 2; return True, y is exactly the same as return True, 2. Commented Aug 6, 2015 at 15:01

2 Answers 2

3

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). 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'>
Sign up to request clarification or add additional context in comments.

Comments

1

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 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.