The eval() function executes the expression given as its argument. The expression is evaluated and parsed as a valid python statement. The expression always a string and it is mandatory for the eval() function.
eval(expression, globals=None, locals=None) #Where expression can be a string to evalate
Takes 3 parameters where the first parameter is mandatory and the other two are optional.
Parameter | Description | Required / Optional |
---|---|---|
expression | This parameter is a string, and it is parsed and executed as a python expression | Required |
globals | It is a dictionary. And it is used to specify the expressions available for execution. | Optional |
locals | It specifies the local variables and methods in the eval() | Optional |
Input | Return Value |
---|---|
Expression | result of the expression |
Both globals and locals omitted | expression is executed in the current scope |
globals exist; locals are omitted | globals will be used for both global and local variables |
both globals and locals exist | result as per the parameter |
# Perimeter of Square
def calculatePerimeter(l):
return 4 * l
# Area of Square
def calculateArea(l):
return l * l
exp = input("Type a function: ")
for l in range(1, 5):
if exp == "calculatePerimeter(l)":
print("If length is ", l, ", Perimeter = ", eval(exp))
elif exp == "calculateArea(l)":
print("If length is ", l, ", Area = ", eval(exp))
else:
print("Wrong Function")
break
Output:
Type a function: calculateArea(l) If length is 1 , Area = 1 If length is 2 , Area = 4 If length is 3 , Area = 9 If length is 4 , Area = 16
from math import *
print(eval('dir()'))
Output:
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'os', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']
from math import *
print(eval('dir()', {}))
# The code will raise an exception
print(eval('sqrt(25)', {}))
Output:
['__builtins__'] Traceback (most recent call last): File "", line 5, in print(eval('sqrt(25)', {})) File " ", line 1, in NameError: name 'sqrt' is not defined
from math import *
print(eval('dir()', {'sqrt': sqrt, 'pow': pow}))
Output:
['__builtins__', 'pow', 'sqrt']
from math import *
a = 169
print(eval('sqrt(a)', {'__builtins__': None}, {'a': a, 'sqrt': sqrt}))
Output:
13.0