0

I know that the function eval executes the string(in the parameter) without the quotes .So what I was just trying was that

x=eval("4*5")  #this works
eval("x=4*5")  #but this doesn't

Please tell where I am wrong!

Nimish Bansal
  • 1,719
  • 4
  • 20
  • 37
  • 1
    While it's fine to be curious about this, using eval or exec is pretty much always the wrong approach to solving a problem. If you tell us what you're trying to do in a larger context, we can tell you a better way to do it. – Alex Hall Aug 26 '17 at 11:28
  • 1
    eval take an expression as arguments. – Kallz Aug 26 '17 at 11:28
  • ya I got it,Thanks . I was just trying to know the use of eval function . I thought whatever is written in the argument is executed as it is. – Nimish Bansal Aug 26 '17 at 11:30

4 Answers4

1

use

exec('x=4*5')

eval evaluates only expressions not assignments.

akp
  • 619
  • 5
  • 12
1

4*5 is an expression, it has a value of 20.

x=4*5 is not an expression and it doesn't have a value. It's a statement, meaning it performs an action.

Alex Hall
  • 34,833
  • 5
  • 57
  • 89
1

eval() runs its string parameter as a python expression. It evaluates the value of that expression. It cannot work with assignments or other statements that are not expressions.

Debanik Dawn
  • 797
  • 5
  • 28
1

eval function has the following structure:

eval(expression, globals=None, locals=None)

The expression argument is parsed and evaluated as a Python expression. It is actually a string expression rather than a assignment.

Ref: Here

Yathartha Joshi
  • 716
  • 1
  • 14
  • 29