简体   繁体   中英

Return multiple values from one function in python

Can I return multiple values from one function and return them all at one into another function?

def function_1():
        one    = "Hello"
        two    = "how"
        three  = "are"
        four   = "you"
        return one, two, three, four

def function_2(one,two,three,four)
        print(one,two,three,four)

function_1()
function_2(one,two,three,four)

And can I return multiple values from one function and distribute each value to a function specific for each value to do some operation? How is this solved in Python?

def function_1():
    if something:
        one    = "Hello"
        return one
    elif something:
        two    = "how"
        return two
    elif something:
        three  = "are"
        return three
    elif something:
        four   = "you"
        return four

def function_for_one(one)
    print(one)

def function_for_two(two)
    print(two)

def function_for_three(three)
    print(three)

def function_for_four(four)
    print(four)

function_1()
function_for_one(one)
function_for_two(two)
function_for_three(three)
function_for_four(four)

First, you have a little mistake in function_1() , you are returning undefined variables hello, how, are, you , instead of doing return "hello", "how", "are", "you" . Alternatively, you can return the variables that store those strings by return one, two, three, four . Also, be aware of tabs, the way you wrote it you are defining function_2() inside of function_1().

As for your first question, there are a couple of ways to do it. One is to parse the first function inside the second given that the second function takes in the same number of arguments that the first returns:

function_2(function_1())

A second way would be to store the values that the first function returns and then parse them into the second function like:

a, b, c, d = function_1()
function_2(a, b, c, d)

With this you can parse them individually into different functions:

function_for_one(a)
function_for_two(b)
function_for_three(c)

And so on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM