-2

im trying to learn python online and am currently on lambda functions but I cant understand this code. Got the code from w3 school.

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

mydoubler = myfunc(2)

print(mydoubler(11))

Ans: 22

I understand the myfunc(n), but isn't lambda supposed to have a func written in front of it like func(n) = lambda n: n+5 or something? Or is the function in front of it just the func(n)? And I understand a*n = 2* 11 in this example but I don't understand how 2 and 11 slots into a and n for this example. Any help or explanation will be very much appreciated.

Thanks!

rickhg12hs
  • 10,638
  • 6
  • 24
  • 42
David Tan
  • 9
  • 1

1 Answers1

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

This creates a new function that accepts one argument, and multiplies that argument (a) by the argument passed to myfunc (n).

mydoubler = myfunc(2)

Therefore, this creates a new function that accepts one argument, and multiplies that argument by 2.

mydoubler(11)

This calls the new function with an argument of 11.

11 * 2 = 22.

Honestly, if you're just starting to learn python, there are easier things you could study than lambdas...

John Gordon
  • 29,573
  • 7
  • 33
  • 58