0

I'm learning the lambda options to return in python and i have a question:

I need to fill the returns in this function:

def func(n):
   if n==0:
      print("finished")
   else:
      return ___
func(5)()()()()()
func(3)()()()
func(8)()()()()()()()()

The output:

finished
finished
finished

I thought this one is a recursive call like return func(n-1) but it doesn't work, and throws an error. Is there an option to overcome the extra empty brackets? count them? do something, because it should be runnable.

Thanks

4
  • You should ask about one question per post, each containing what you've tried and researched so far Commented Apr 16, 2022 at 16:16
  • Why are there empty parentheses in the first place? Are they part of some assignment or homework that you are doing? Commented Apr 16, 2022 at 16:16
  • () is the function call. These are python basics... If you have def foo():..., then foo is the function itself, and you can call it as foo(). And you can return a function from a function Commented Apr 16, 2022 at 16:19
  • Not homehwork, just questions that "should help you get better with lambda expressions"... Commented Apr 16, 2022 at 16:19

2 Answers 2

1

You're right about needing to use lambdas and func n-1, specifically

return lambda: func(n-1)

This returns a lambda that doesn't need any parameters passed in, to handle the brackets, and the return of the is the function being called with n-1, which in most calls you're making, is returning the next lambda function call

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

Comments

0

The operator () is the function call. So for example:

def foo():
   print('Foo executed')

def bar():
   # We return the foo FUNCTION itself, without calling it.
   return foo

In the above code, if you execute foo(), it'll print "Foo executed". But if you execute bar(), it will return foo, which is the function. So you can execute bar()(), where the first () is executing the function bar, returning foo, and then with the second (), you call the returned foo function.

Edit: When I typed it, you removed the what are those bunch of () because they are new to you... But I just leave it there maybe it'll help.

1 Comment

Yes I know how to "solve it" with another fuction, but I didn't know the syntax should be like Sayse wrote dotn here. Thank you!

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.