0

As I read from the documentation eval() function is used to evaluate an Expression.

But Python is doing that by default right. I mean

>>> x=10
>>> x+2
12
>>> eval('x+2')
12
>>> 

So when I enter x+2 python evaluated/interpreted that statement, so why again using eval() function here.

And I thought using it in a python program may cause some difference so I tried that as well.

x=10
x=x+12
print(x)
print(eval('x+13'))
print(x+13)

With output as

22
35
35

So print(x+13) and print(eval('x+13')) are printing same results and I believe doing same action internally.

Am I missing any best or dedicated use cases of eval() function in Python ? Or its just what I understand ?

Thank you in Advance.

Raja G
  • 5,973
  • 14
  • 49
  • 82
  • You may be getting the input from somewhere else (from a user, from another program etc.). You cannot just execute them like you would execute `x+2`. Not all programs run in the interactive interpreter. – ayhan Mar 24 '18 at 19:47
  • @ayhan, can you give me one example ? – Raja G Mar 24 '18 at 19:50
  • `eval(input('please enter an arithmetic expression: '))` would return 5 if the user enters `2+3` for example. The user normally doesn't have access to the program so they can only supply inputs. – ayhan Mar 24 '18 at 19:58

0 Answers0