How To Get A Single Output From A Function With Multiple Outputs?
I have the following simple function: def divide(x, y): quotient = x/y remainder = x % y return quotient, remainder x = divide(22, 7) If I accesss the variable x I
Solution 1:
You are essentially returning a tuple, which is an iterable we can index, so in the example above:
print x[0]
would return the quotient and
print x[1]
would return the remainder
Solution 2:
You have two broad options, either:
Modify the function to return either or both as appropriate, for example:
defdivide(x, y, output=(True, True)): quot, rem = x // y, x % y ifall(output): return quot, rem elif output[0]: return quot return rem quot = divide(x, y, (True, False))
Leave the function as it is, but explicitly ignore one or the other of the returned values:
quot, _ = divide(x, y) # assign one to _, which means ignore by convention rem = divide(x, y)[1] # select one by index
I would strongly recommend one of the latter formulations; it's much simpler!
Solution 3:
You can either unpack the return values when you call your method:
x, y = divide(22, 7)
Or you can just grab the first returned value:
x = divide(22, 7)[0]
Post a Comment for "How To Get A Single Output From A Function With Multiple Outputs?"