0

I'm new to Python and I'm trying to understand how this function is working:

def myfunc(n):
  return lambda a : a * n

mytripler = myfunc(3)

print(mytripler(11))

So I pass 3 to myfunc and I get 3a as a returned value. I don't understand how value 11 which I send as an argument from mytripler function gets involved with myfunc. When I try to write the function like this I can't get the same result:

def myfunc(n, a):
  return lambda a : a * n

print (myfunc(11, 3))

Can someone explain me?

2
  • Functions are objects. You have defined another function and returned the actual function you just defined. You could make it clearer if you use regular "def" syntax inside the (poorly named) myfunc. Commented Sep 4, 2022 at 1:35
  • The a argument to myfunc is not related to the a argument of the function that myfunc returns. Commented Sep 4, 2022 at 1:50

1 Answer 1

1

To make sure you understand it better, let's rewrite your example and see the output at each step:

def myfunc(n):
  return lambda a : a * n

mytripler = myfunc(3)
type_of_mytripler=type(myfunc(3))
print(f'after the first call, you get {mytripler=} with {type_of_mytripler=}')

result=mytripler(11)
type_of_result=type(mytripler(11))
print(f'after the second call, you get {result=} with {type_of_result=}')

You get the following output:

after the first call, you get mytripler=<function myfunc.<locals>.<lambda> at 0x7fd196415940> with type_of_mytripler=<class 'function'>
after the second call, you get result=33 with type_of_result=<class 'int'>
33

As you can see, during the first call you actually return a lambda function. Afterward, you have to pass a new arg to your function to execute it and get a final result. You could also rewrite your example as result=myfunc(3)(11) to achieve the same result.

To summarize, keep in mind that in Python functions are objects as well. That is, you can both pass them as arguments to other functions or return them. Obviously, you can't get a final result out of a function itself unless you execute it using round brackets. What you effectively created is a function that returns a function.

Check the topic decorators in Python which might be a little bit complicated now but should give you a general idea about passing/returning functions as objects. This Real Python article is a good intro to this topic. For now, you might find a few paragraphs about the functions in Python most useful

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

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.