Syntax error when using assignment (lambda) in eval ()?

When i type next

eval("mult = lambda x,y: (x*y)")

Am I getting this as an error? What's happening?

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    mult = lambda x,y: (x*y)
         ^
SyntaxError: invalid syntax

What am I doing wrong? If I enter the expression as is (no eval), I get no error and can use it multfor my content.

+3
source share
3 answers

You want to use exec instead of eval. I don’t know why you would like to do this, though, when you can just usemult = lambda x,y : (x*y)

>>> exec("mult = lambda x,y : (x*y)")
>>> mult
<function <lambda> at 0x1004ac1b8>
>>> mult(3,6)
18
+10
source

Eval makes expressions; they are not assigned.

>>> eval("lambda x,y: y*x")
<function <lambda> at 0xb73c779c>
>>> eval("lambda x,y: y*x")(2, 4)
8

You must assign the eval'd expression to the variable:

>>> mult = eval("lambda x,y: y*x")
>>> mult(2, 3)
6
+8
source
mult = eval("lambda x,y: (x*y)")
+2
source

All Articles