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

Python executing a string as code

Python executing a string as code

Document Object Reference Manual Python3 Examples

Given a string of code, use exec() to execute the string of code.

Example 1: using the built-in method exec()

def

exec_code

(

)

:

LOC

=

"""

def factorial(num): fact=1 for i in range(1,num+1): fact = fact*i return fact print(factorial(5))

"""

exec

(

LOC

)

exec_code

(

)

The output of the code above is:


120

Document Object Reference Manual Python3 Examples