Home > Enterprise >  How to use one output of a function and store a second one=
How to use one output of a function and store a second one=

Time:08-26

So I have a function which outputs 2 values:

def example(a, b):
    c = math.floor(a / b)
    a  = a%b
    return (c, a)

I want to use this function this way:

print("text: ", c)

How can I use the function and print c, but store x for later?

CodePudding user response:

First, you need to call the function and assign its return values to some variables:

x, y = example(42, 5)

Then you can print the results:

print(x)
print(y)

CodePudding user response:

You can even skip the variable assignment if you wish so

print("text:", example(a, b)[0])

but it's ugly

CodePudding user response:

Your function will return a tuple containing the two values. You can assign the result of calling your function to a variable.

Note,

  • that the parentheses are not required in your return statement.
  • you can replace math.floor(a / b) with a // b which will also do a floor division.

An example is shown below where the result of calling the function is unpacked into two variables, c and a.

def example(a, b):
    c = a // b
    a  = a % b
    return c, a
    
c, a = example(6, 3)

print("text:", c)

Alternatively, you can also store the result in a single variable that references your tuple as follows:

data = example(6, 3)

print("text:", data[0])
  • Related