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

前端 未结 8 670
执笔经年
执笔经年 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:38

    You cannot return two values, but you can return a tuple or a list and unpack it after the call:

    def select_choice():
        ...
        return i, card  # or [i, card]
    
    my_i, my_card = select_choice()
    

    On line return i, card i, card means creating a tuple. You can also use parenthesis like return (i, card), but tuples are created by comma, so parens are not mandatory. But you can use parens to make your code more readable or to split the tuple over multiple lines. The same applies to line my_i, my_card = select_choice().

    If you want to return more than two values, consider using a named tuple. It will allow the caller of the function to access fields of the returned value by name, which is more readable. You can still access items of the tuple by index. For example in Schema.loads method Marshmallow framework returns a UnmarshalResult which is a namedtuple. So you can do:

    data, errors = MySchema.loads(request.json())
    if errors:
        ...
    

    or

    result = MySchema.loads(request.json())
    if result.errors:
        ...
    else:
        # use `result.data`
    

    In other cases you may return a dict from your function:

    def select_choice():
        ...
        return {'i': i, 'card': card, 'other_field': other_field, ...}
    

    But you might want consider to return an instance of a utility class, which wraps your data:

    class ChoiceData():
        def __init__(self, i, card, other_field, ...):
            # you can put here some validation logic
            self.i = i
            self.card = card
            self.other_field = other_field
            ...
    
    def select_choice():
        ...
        return ChoiceData(i, card, other_field, ...)
    
    choice_data = select_choice()
    print(choice_data.i, choice_data.card)
    

提交回复
热议问题