Easy Tutorial
❮ Python String Lower Python Upper Lower ❯

Python3 exec Function

Python3 Built-in Functions


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

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

Python3 Built-in Functions

❮ Python String Lower Python Upper Lower ❯