Asked 7 years ago
23 Mar 2017
Views 1844
Phpworker

Phpworker posted

PYTHON : eval vs exec

Difference between eval and exec function in Python

so what is pros and cons of eval vs exec in Python or both same no difference
shyam

shyam
answered Aug 9 '21 00:00

the main difference between eval and exec is the functionality,
exec is server as king and eval are like one of the solider.

exec() function is execute anything which is passed in as an argument. it can run Python code itself. so exec() function is a very powerful and very dangerous function
eval() function is run arithmetic operation only like x*x and if x is 3 then eval will run x*x and give you returns is 9, that it is, eval() cant able to run any code of Python except the simple code

sample code of exec() function :

exec('print("hello world")')


it will print hello world

sample code of eval() function :

eval('print("hello world")')

it will print hello world again


let me explain in detail by example :

x=int(input("Enter the value of x:"))
expr = 'x*x'
y = eval(expr)
print(y)


you see i used eval() function to multiply x , i passed expression as string in eval() function
so if run above code
it will ask to input for value of x and if you enter 3 it will result 9

Enter the value of x: 3
9


let's introduce the exec() code in the above code

exec('x=int(input("Enter the value of x:"))')
expr = 'x*x'
y = eval(expr)
print(y)


now you can see i use exec() function to run x=int(input("Enter the value of x:")) instead of direct Python
and other code work same as above

Enter the value of x: 3
9

in output we did not notice that some code executed by exec() function


but if you try to run eval ('x=int(input("Enter the value of x:"))') it will generate error :
x=int(input("Enter the value of x:"))
^
SyntaxError: invalid syntax

lain

lain
answered Aug 9 '21 00:00

one common thing between eval() and exec() is that they are not good to use .
eval() and exec() both functions are dangerous and not advised to use because it expose the hidden value or gives access to database.
anything can happen with eval() and exec() funtions
Post Answer