How to use returned result from inner function as a parameter in the outer function?

Question:

I have a question regarding how to use the returned result from the inner function as a parameter in the outer function.

I tried the following code, but the result was not what I expected:

def outer_function(a,b):
    def inner_function(c):
        inner_result = c * 100
        return inner_result 
    return inner_function 
    outer_result = a * b * inner_result 
    return outer_result

some_func = outer_function(10,9)
some_func(9)

I expected the result from the some_func(9) as 9 * 100 * 10 * 9 = 81000; instead, the result turned out to be 900.

I am wondering what I did wrong and how I can use the inner_result as a parameter in the outer_function?

Asked By: vae

||

Answers:

When you returned inner_function on line 5. The function ended, so line 6 and 7 didn’t get executed.

Answered By: mzebin

outer_function (like all functions) can only return a single value, yet you’re attempting to return both the inner_function, and the outer_result. The first return ends the function, leading to erroneous behavior.

If you don’t want to incorporate the outer_result calculation into inner_function (I’d just do that), you could wrap it in another function that carries out the calculation. That could be done via a lambda, or another full def:

def outer_function(a,b):
    def inner_function(c):
        inner_result = c * 100
        return inner_result
    return lambda c: a * b * inner_function(c)

or

def outer_function(a,b):
    def inner_function(c):
        inner_result = c * 100
        return inner_result
    def second_inner_function(d):
        return a * b * inner_function(d)
    return second_inner_function

Although, again, the a * b * calculation should likely just be added into inner_function unless for conceptual reasons you really wanted to keep it separate.

Answered By: Carcigenicate

I got you simple approach for you with some little tweaks in the code:

    def outer_function(a,b):
    def inner_function(c):
        inner_result = a * b * c * 100
        return inner_result 
    return inner_function 
    

some_func = outer_function(10,9)
print(some_func(9))

I hope you can easily understand it now.

Answered By: Blazing Sword
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.