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
exec(object[, globals[, locals]])
where
Parameter | Required/ Optional | Description |
---|---|---|
object | Required | A string or code object. The string is parsed and evaluated, or the code object is executed. |
globals | Optional | A dictionary. This is used as global namespace. |
locals | Optional | Any 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
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
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
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.