eval and exec¶
Let us understand how we can use eval
and exec
in Python.
- Typically we perform arithmetic operations like this
a = b + c
. - We can also use
eval
andexec
for the same. eval
typically evaluates the expression. We need to assign the value to some variable when we useeval
.exec
executes the statement.
In [1]:
b = 10
In [2]:
c = 20
In [3]:
a = b + c
In [4]:
a
Out[4]:
30
In [5]:
eval('b + c') # Typically we assign the result of eval to a variable or object
Out[5]:
30
In [6]:
exec('d = b + c') # variable or object will be created when we use exec
In [7]:
d
Out[7]:
30
In [8]:
def calc(a, b, op):
return eval(f'{a} {op} {b}')
In [9]:
calc(1, 2, '+')
Out[9]:
3
In [10]:
calc(10, 20, '*')
Out[10]:
200