Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python exec Built-in Statement

Python exec Built-in Statement

Python built-in function Python built-in function


Description

exec executes Python statements stored in a string or file; compared with eval, exec can execute more complex Python code.

It should be noted that in Python 2, exec is not a function but a built-in statement, although Python 2 has an execfile() function. It can be understood that Python 3 integrated the functions of the exec statement and the execfile() function into a new exec() function.

Syntax

The syntax of exec is as follows:


exec obj

Parameters

Return Value

The return value of exec is always None.


Example

The following shows examples of using exec:

Example 1

exec

'

print "Hello World"

'

Hello

World

A single-line statement string

exec

"

print 'runoob.com'

"

runoob

.

com

A 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 result:


60
33
34

Python built-in function Python built-in function