-4

Imagine I have a function like this:

def func(x):
    a = lambda b : x + b
    a = lambda c : a * c
    return a;

How can I give an argument to the second lambda? Is this even possible, by the way?

And I was thinking: Is there a way to give one argument and b, c so both use that argument?

I tried to pass parameters one by one like this:

(I want print(a(6)) to print 60)

myFunc = func(4);
a = myFunc(6)
print(a(6));

And I end up with this error:

line 4, in <lambda>
    a = lambda c : a * c
TypeError: unsupported operand type(s) for *: 'function' and 'int'
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 1
    1- what don't you understand about the error message? 2- what did you expect `a(6)` to be? [ask] and [mre] – Julien Aug 02 '23 at 05:20
  • Yes, it's really not clear what you want that last print to produce. A single value like 60? or two values? – Mark Aug 02 '23 at 05:25
  • The first two lines in the function don’t do anything, since you overwrite `a` again and again. Only the last assignment to `a` sticks. So it’s unclear what you expect to happen here. – deceze Aug 02 '23 at 05:27
  • 1
    `a = lambda b : x + b` still doesn’t do anything, as it gets overwritten. – deceze Aug 02 '23 at 05:33
  • 1
    There’s also no reason to use lambdas here, the PEP8 style guide would prefer you use normal `def` functions. – deceze Aug 02 '23 at 05:36

1 Answers1

-4

The error you encountered is due to the fact that you are trying to perform the multiplication operation between a lambda function (a) and an integer (c). In Python, you cannot directly multiply a function with an integer.

To achieve what you want, you can create a single lambda function with two arguments (b and c) and return their sum and product, like this:

def func(x):
  a = lambda b, c: (x + b, x * c)
  return a

Now, you can call the func function and then the returned lambda function with two arguments:

myFunc = func(4)
result_sum, result_product = myFunc(6, 6)
print("Sum:", result_sum)       # Output: Sum: 10 (4 + 6)
print("Product:", result_product)  # Output: Product: 24 (4 * 6)

Here, we define a lambda function with two arguments b and c, and we return a tuple containing their sum and product. By doing this, you can use a single lambda function to compute both the sum and the product of the input values.

If you need to keep the intermediate results and use them in subsequent operations, you can store them in variables and pass them to the lambda function as needed. However, the lambda function itself can only take the arguments specified in its definition.

Sampath Wijesinghe
  • 789
  • 1
  • 11
  • 33