2

I am new in stackflow. I will so thankful if someone can help me.

I have to resolve this:

Define a nested function called nested_sum, where in the first part of the function you accept an argument called x, and in the second part (the function inside) you take another argument called y. In the function inside you have to calculate the sum of x and y.

To test your function create a variable called res_1 where you pass the x argument to nested_sum, and then create a variable called res_2 where you pass the y argument of the res_1 variable to get the final solution.

Have x equal 2 for res_1 and y equal 10 for res_2.

After looking on the internet I found a similar code, but I don't really understand how it works!

def nested_sum(x):
    def in_sum(y):
        return x+y
    return in_sum

res_1 = nested_sum(2)
res_2 = res_1(10)

Thank you

1
  • If you got your answer, please mark one as accepted clicking huge checkbox near it. Commented May 3, 2020 at 19:55

3 Answers 3

4

First of all you need to realise res_1 is simply the in_sum() function.

Therefore as per your code:

nested_sum(2) puts x = 2 and then returns the in_sum() function. res_2 = res_1(10) = in_sum(10)

Therefore x = 2 and y = 10, so thus

x + y = 2 + 10 = 12

Sign up to request clarification or add additional context in comments.

Comments

0

You can write the code (easier to understand) as follows:

def nested_sum(x):
    def in_sum(y):
        return x+y
    return in_sum



res_1 = nested_sum(2) #nested_sum return in_sum(y) location with x=2 so --> res_1= in_sum (2+y)
res_2 = res_1(10)     #Cause res_1 points in_sum(2+y) res2=in_sum(2+10)=12

1 Comment

Thank so much. It is means that assigning a variable the result of a nested function the inner functions are methods of this variable?
0

First of all, function in Python is an object. Think of it as a piece of paper where it is written what arguments it needs an what to do with them.

nested_sum(2) creates a new piece of paper where it is writen: «take the 𝑦 argument, add 2 to and return it.»

nested_sum(𝑥) creates a new piece of paper where it is writen: «take the 𝑦 argument, add 𝑥 and return it.»

Let me rename variables in your code:

def increaser_function_maker(x):

    def the_new_function(y):
        return x + y

    return the_new_function

function_that_takes_number_and_adds_two_to_it = increaser_function_maker(2)
result = function_that_takes_number_and_adds_two_to_it(10)

There is another way to make this function. Maybe it will be easier to understand:

def increaser_function_maker(value_to_add):
    return lambda i: i + value_to_add

1 Comment

Thank you. I understand better from all answers.

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.