YouTip LogoYouTip

Python Func Exec

# Python2.x Python exec Built-in Statement [![Image 3: Python Built-in Functions](#) Python Built-in Functions](#) * * * ## Description exec executes Python statements stored in strings or files. Compared to eval, exec can execute more complex Python code. > It should be noted that in Python2, exec is not a function but a built-in statement. However, Python 2 has an execfile() function. It can be understood that Python 3 integrated the functionality of the exec statement and the execfile() function into a new exec() function. ### Syntax Here is the syntax for exec: exec obj ### Parameters * obj -- The expression to be executed. ### Return Value The return value of exec is always None. * * * ## Examples The following examples demonstrate the use of exec: ## Example 1 >>>exec'print "Hello World"'Hello World# Single-line statement string>>>exec"print ''"# 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: 603334 [![Image 4: Python Built-in Functions](#) Python Built-in Functions](#)
← Python Func TypePython Func Unichr β†’