John Diamond
John Diamond

Reputation: 31

How to use output for one function as parameter for another

I am trying to work on one file, and I have two functions a and b.

suppose a was:

def A(num1,num2):
    num3 = num1 + num2

def B(num3,num4):
    num5 = num3*num4

how would I use the output from A(num3) and use it in B?

Upvotes: 2

Views: 20316

Answers (3)

Lekha B
Lekha B

Reputation: 75

1) RETURN the output of function A.

def A(num1,num2):
    num3 = num1+num2
    return num3

2) When you call function A, store the result in another variable.

result = A(12,14)

The variable result will now contain the value of (num1+num2). We will pass this as an argument to function B.

3) When calling function B, in place of num3, pass the value stored in 'result'. The second argument can be any number.

B(result,11)

Upvotes: 2

Avivex1000
Avivex1000

Reputation: 61

what your looking for is the "return" basically it allows your function to give an output that you could use later.

for example:

num1 = 1
num2 = 2

def a(num1, num2):
    return num1 + num2

def b(num3,num4):
    return num3*num4

num3 = a(num1, num2)
num5 = b(num3, num2)

in general this is pretty basic and not very good code practice because i don't know what your trying to solve. further information might help writing a better use of code for your problem :) i wouldn't actually use this code other than to demonstrate the return in this situation just so you know, while defining a function doesn't actually do anything until you call it so the fact you gave it the same name does not bind the actual values in any way.

i would recommend you read more about python basics regardless. good luck!

Upvotes: 0

Green Cloak Guy
Green Cloak Guy

Reputation: 24681

First, you need your functions to return values. Currently A() is just computing the value num1 + num2 and not doing anything with it. If you want it to pass back the answer, you have to add a return statement at the end of it:

def A(num1,num2):
    num3 = num1 + num2
    return num3

Next, if you want to pass the result of that function into function B, you'd do this:

...
some_var = B(A(num1, num2), num4)
...

See, it works the same as calling a function anywhere else, except it's inside the parentheses and in the same place as you might otherwise put a variable.

Upvotes: 4

Related Questions