#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

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.


exec(source, globals = None, locals = None)
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 function executes the arbitrary Python object given in the source arguments.

Example with strings:
exec("a = 1 + 3\nprint(a)")
code = "print('Hello, World!')"
//Hello, World!
add_string = "def add(a, b):\n    print('{} + {} = {}'.format(a, b, a + b))\nadd(30, 50)"
//30 + 50 = 80
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. Examples:

code_string = "def prod(a, b):\n    print('%s * %s = %s'%(a, b, a*b))\nprod(10, 50)"
compiled_object = compile(code_string, '', 'exec')
//10 * 50 = 500

Note: You should be very 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.