ExampleEdit & Run
#Use the exec() Function

#A string containing valid Python code
source_string = """
def add(a, b):
    return a + b
a = 100
b = 200
print(add(a, b))
"""
#Compile the source string using the builtin compile() function
code_object = compile(source_string, "<string>", "exec")

#call the exec function with the code object
exec(code_object)
copy
Output:
300 [Finished in 0.011634790804237127s]

The exec() function enables execution of dynamically-generated code.

It takes one required argument, the object to be executed, this can be a string containing valid Python code or a code object generated by the builtin compile() function.

Syntax:
exec(source, globals = None, locals = None)
copy
source A required argument representing the arbitrary Python code to be executed. It can be in form of a string or a code object generated by the builtin compile() function.
globals Optional dictionary argument representing the global namespace that should be used for the execution
locals Optional dictionary argument representing the local namespace that should be used for the execution

The exec() function executes the arbitrary Python object given in the source arguments. The function returns None, this is unlike eval() which returns the results of the evaluation.

Example with strings

ExampleEdit & Run
exec("a = 1 + 3\nprint(a)")

code = "print('Hello, World!')"
exec(code)

add_string = "def add(a, b):\n    print('{} + {} = {}'.format(a, b, a + b))\nadd(30, 50)"
exec(add_string)
copy
Output:
4 Hello, World! 30 + 50 = 80 [Finished in 0.010020981077104807s]

As shown above , we are passing the valid Python code as a python string. In the following example, we use a multi-line string.

ExampleEdit & Run

snippet = '''
print('Started!')

def add(a, b):
    result = a + b
    return f"{a} + {b} = {result}"

print( add(10, 20) )
print( add(50, 50) )
print( add(30, 100) )

print('Done!')
'''

exec(snippet)
copy
Output:
Started! 10 + 20 = 30 50 + 50 = 100 30 + 100 = 130 Done! [Finished in 0.01034534489735961s]

Using compiled code object

The built-in compile() function is used to compile a Python code from a string, it returns a code object which can then be executed by passing it as an argument to the exec() function. 

In this approach, we first compiles the code snippet with compile() then passes the returned code object to exec().

ExampleEdit & Run
code_string = "def prod(a, b):\n    print('%s * %s = %s'%(a, b, a*b))\nprod(10, 50)"

compiled_object = compile(code_string, '', 'exec')

exec(compiled_object)
copy
Output:
10 * 50 = 500 [Finished in 0.010723662097007036s]

Passing the 'exec' parameter as the third argument of the compile() function tells the function that it should compile the snippet for execution by the exec() function. This is important because the function is also used to compile code for other functions such as eval().

Note:  you should be careful when using the exec() function as it can potentially cause unintended consequences, such as security vulnerabilities. This is especially the case when you are executing the code from users or from external sources. In such cases, it is wise to ensure that you properly validate and sanitize the user’s input before executing it. This will ensure that any malicious code is not executed and thus help mitigate potential attack vectors.