How can I return two values from a function in Python?

前端 未结 8 804
执笔经年
执笔经年 2020-11-22 12:14

I would like to return two values from a function in two separate variables. For example:

def select_choice():
    loop = 1
    row = 0
    while loop == 1:         


        
8条回答
  •  暖寄归人
    2020-11-22 12:39

    I would like to return two values from a function in two separate variables.

    What would you expect it to look like on the calling end? You can't write a = select_choice(); b = select_choice() because that would call the function twice.

    Values aren't returned "in variables"; that's not how Python works. A function returns values (objects). A variable is just a name for a value in a given context. When you call a function and assign the return value somewhere, what you're doing is giving the received value a name in the calling context. The function doesn't put the value "into a variable" for you, the assignment does (never mind that the variable isn't "storage" for the value, but again, just a name).

    When i tried to to use return i, card, it returns a tuple and this is not what i want.

    Actually, it's exactly what you want. All you have to do is take the tuple apart again.

    And i want to be able to use these values separately.

    So just grab the values out of the tuple.

    The easiest way to do this is by unpacking:

    a, b = select_choice()
    

提交回复
热议问题