Python3 exec Function
Description
The exec
function executes the Python statements stored in a string or file. Unlike eval
, exec
can execute more complex Python code.
Syntax
Here is the syntax for exec
:
exec(object[, globals[, locals]])
Parameters
object: Required parameter, representing the Python code to be executed. It must be a string or a code object. If
object
is a string, it is parsed as a set of Python statements and then executed (unless a syntax error occurs). Ifobject
is a code object, it is simply executed.globals: Optional parameter, representing the global namespace (stores global variables). If provided, it must be a dictionary object.
locals: Optional parameter, representing the current local namespace (stores local variables). If provided, it can be any mapping object. If this parameter is omitted, it takes the same value as
globals
.
Return Value
The return value of exec
is always None
.
Examples
Below are examples of using exec
:
Example 1
>>> exec('print("Hello World")')
Hello World
# Single-line statement string
>>> exec("print ('tutorialpro.org')")
tutorialpro.org
# Multi-line statement string
>>> exec ("""for i in range(5):
... print ("iter time: %d" % i)
... """)
iter time: 0
iter time: 1
iter time: 2
iter time: 3
iter time: 4
Example 2
x = 10
expr = """
z = 30
sum = x + y + z
print(sum)
"""
def func():
y = 20
exec(expr)
exec(expr, {'x': 1, 'y': 2})
exec(expr, {'x': 1, 'y': 2}, {'y': 3, 'z': 4})
func()
Output:
60
33
34