Easy Tutorial
❮ Python String Decode Python Func Divmod ❯

Executing Strings as Code in Python

Python3 Examples

Given a string of code, use exec() to execute the string 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()

Executing the above code outputs:

120

Python3 Examples

❮ Python String Decode Python Func Divmod ❯