Home > OS >  How do I store the second returned value from a function?
How do I store the second returned value from a function?

Time:05-22

Is there a way to store only the second return value from a function? Im looking for something like this:

def func(pos, times_clicked, cost):
    if buy_image_rect.collidepoint(pos) and times_clicked >= cost:
        times_clicked -= cost
        cost  = 5
    return cost, times_clicked

# But I want to get the second return value for times_clicked. It doesn't work like this:
times_clicked = func(event.pos, times_clicked, cost) 

I need to get both of the return values for different things. Please help!

CodePudding user response:

The return value is a tuple with two components. Assign the result to two separate variables:

cost, times_clicked = func(event.pos, times_clicked, cost) 

CodePudding user response:

times_clicked actually holds both values.

When you return a few values from a function a tuple is returned.

You tuple can be spread into variables like that:

var_1, var_2 = (1, 2) # var_1 == 1, var_2 == 2

Same when you call a function that returns two values:

cost, times_clicked = func(event.pos, times_clicked, cost) 

CodePudding user response:

The return value of a function with more than one variable would return a tuple with the values when the function is called.

To access the values, by referring to the index number of the tuple corresponding to the order of return values assigned in the function.

tup= func(event.pos, times_clicked, cost)
cost, times_clicked= tup #(var1,var2)
  • Related