0

Simple question on how to link (or string together) multiple functions that depend on each other. I have the following example function (in Jupyter):

### First function
def function_one():

    ## process one
    a = "one" + "two"
    print(a)

    ## process two
    b = "red" + "blue"
    print(b)

    ## process three
    c = "this" + "sucks"
    print(c)

    return a, b, c

### Second function
def function_two(a, b, c):

    ## process four
    d = a + b
    print(d)

    ## process five
    e = b + c
    print(e)

    ## process six
    f = a + c
    print(f)


    return d, e, f

### Third function
def function_three():

    g = a + b + c + d + e + f
    print(g)

    return g

### Calling functions
initial = function_one()
second = function_two(initial)
third = ... #I can't get past the following error to even link this function in

The first function works when called, but when I try to send that data downstream to the second function, I get this error:

onetwo
redblue
thissucks
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-10-7c5562b97c86> in <module>
      1 initial = function_one()
----> 2 second = function_two(initial)

TypeError: function_two() missing 2 required positional arguments: 'b' and 'c'

How do I remedy this?

0

2 Answers 2

4

When returning multiple objects, you are actually returning a tuple. Ex:

>>> def foo():
>>>     return 1, 2, 3

>>> type(foo())
<class 'tuple'>

So, right now the whole tuple is treated as argument a and hence b and c are missing. In order to pass that on as 3 separate arguments, you need to unpack that tuple:

initial = function_one()
second = function_two(*initial)
third = function_three(*initial, *second)
Sign up to request clarification or add additional context in comments.

1 Comment

This is... magical. Many thanks. I like the other answer, too, but I think yours is the simplest way. Thoughts?
2

Assign the return values to variables then pass it to the second function:

a, b, c = function_one()
function_two(a, b, c)

For your third function you need it to accept parameters as well

def function_three(a, b, c, d, e, f):
    g = a + b + c + d + e + f
    print(g)
    return g

Then putting it all together:

a, b, c = function_one()
d, e, f = function_two(a, b, c)
g = function_three(a, b, c, d, e, f)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.