Python Exec() function

Published February 15, 2022

Python's exec() function allows the dynamic execution of Python programs, which can either be objects or string codes. Programs written in object code are just executed, whereas programs written in strings are parsed as Python statements and are then executed unless a syntax error occurs.

It is essential to ensure that the returned statements are not outside the function definitions or outside the context of the passed code.

Let's take a look at the syntax of the exec () function.

 

Syntax

exec(object[, globals[, locals]])

where:

  • An object is the object or string code

  •  Globals- a dictionary

  •  Locals-  the mapping object

Now let's see how this function works in the example below

 

Example

In the example below, the exec() function will double-execute the sum of the two numbers

exp = 'print("The Multiplication of 6 and 9 is", (6*9))'

exec(exp)

 

Output

The Multiplication of 6 and 9 is 54

 

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

265 Views