Python eval() function

Published February 15, 2022

eval() is a built-in method or function that works by parsing an expression and running it as the program executes.

 

Syntax

Let's look at the syntax of the eval() function.

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

·         Expression- the string  parsed  and evaluated as Python expression

·         Globals-  this includes the dictionary

·         Locals- used to map the object

In order to understand how to use the Eval() syntax more thoroughly, let's look at an example:

 

Example

evaluate = 'a*(a+5)*(a+7)'

print(evaluate)

print(type(evaluate))

a = 5

print(type(a))

exp = eval(evaluate)

print(exp)

print(type(exp))

Output

Running the above code will produce the following output

a*(a+5)*(a+7)
<class 'str'>
<class 'int'>
600
<class 'int'>

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

227 Views