Python exec()

Python exec() builtin function is used to execute Python code dynamically, given to it via a string or code object.

In this tutorial, we will learn about the syntax of Python exec() function, and learn how to use this function with the help of examples.

Syntax

The syntax of exec() function is

</>
Copy
exec(object[, globals[, locals]])

where

ParameterRequired/
Optional
Description
objectRequiredA string or code object. The string is parsed and evaluated, or the code object is executed.
globalsOptionalA dictionary. This is used as global namespace.
localsOptionalAny mapping object. This is used as local namespace.

Examples

1. Execute Code in String

In this example, we take a string and execute it as Python code using exec() function.

Python Program

</>
Copy
code = 'print("Hello World")'
exec(code)

Output

Hello World

2. Execute Code Object

In this example, we take a string and execute it as Python code using exec() function.

Python Program

</>
Copy
x = 'print("Hello World!")\nprint("hello world")'
object = compile(x, '', 'exec')
exec(object)

Output

Hello World!
hello world

3. Execute with Global Variables

In this example, we provide globals parameter to exec() function. Values for the variables in this dictionary are used for execution.

Python Program

</>
Copy
code = 'print(x+5)\nprint("hello world")'
globals = {'x': 5}
exec(code, globals)

Output

10
hello world

Conclusion

In this Python Tutorial, we have learnt the syntax of Python exec() builtin function, and also learned how to use this function, with the help of Python example programs.