2
#to add and multiply numbers using lambda in python
a=int(input("a number: "))
b=int(input("another number: "))
print("the sum is {}".format(lambda a,b:a+b))
print("the multiple is {}".format(lambda a,b:a*b))

i tried to add and multiply two numbers using lambda but i don't know why it shows error like this.I am a beginner to programming the error is :

the sum is <function <lambda> at 0x000001B6BF941B88>
the multiple is <function <lambda> at 0x000001B6BF893798>

2
  • 2
    because lambda is a function. You need to actually call it to get a value... why are you using lambda here? You could do (lambda a,b: a+b)(a,b) but that's just a clumsy way of doing a + b... Commented May 12, 2020 at 14:44
  • 2
    What are the lambdas for? Just use a+b and a*b. Commented May 12, 2020 at 14:44

4 Answers 4

3

You create a function, but don't actually call it. You can change this in two ways: call the lambda or don't use a lambda function. In this case the second would be better, but if you just want to learn about lambda functions you might use the first.

print("the sum is {}".format((lambda a,b:a+b)(a, b)))
print("the multiple is {}".format((lambda a,b:a*b)(a, b)))

The change I made was to replace the lambda with (lambda a,b:a+b)(a, b)

or just remove the lambda

print("the sum is {}".format(a+b))
print("the multiple is {}".format(a*b))

This would be the better option in this case.

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

Comments

1

lambda is the way of writing anonymous function but they are still functions you need to call them.

a=int(input("a number: "))
b=int(input("another number: "))
print("the sum is {}".format((lambda a,b:a+b)(a,b)))
print("the multiple is {}".format((lambda a,b:a*b)(a,b)))

Output:

a number: 1
another number: 2
the sum is 3
the multiple is 2

1 Comment

thanks for the help, it was my first stack question ,so i am very happy to get help i did not even expect.
1

There is no error in your output. Since lambda is a function, when you print it you see <function <lambda> at 0x000001B6BF941B88>.

If you want to invoke it, try:

a=int(input("a number: "))
b=int(input("another number: "))
sum_func = lambda a,b:a+b
product_func = lambda a,b:a*b
print("the sum is {}".format(sum_func(a,b)))
print("the multiple is {}".format(product_func(a,b)))

2 Comments

thanks a lot,it sank to my mind now, i thought using lambda like that would already mean i called the lambda function but i get it now.
Happy to help :)
1

Try storing it in a variable.

    #to add and multiply numbers using lambda in python
    a=int(input("a number: "))
    b=int(input("another number: "))
    add = lambda a,b:a+b
    mult = lambda a,b:a*b
    print("the sum is {}".format(add(a,b)))
    print("the multiple is {}".format(mult(a,b)))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.