Python built-in Method - exec()

The exec() method is a built-in function in Python that executes a string as a Python statement and does not return a value. The statement can be a single line or multiple lines of Python code.

Here is the syntax for exec() method:

ref‮t re‬o:theitroad.com
exec(source, globals=None, locals=None, /)

where source is a string that contains the Python code to be executed, and globals and locals are dictionaries that specify the global and local namespaces used for the execution (by default, globals and locals are the current global and local namespaces).

Here's an example of how to use exec():

x = 10
y = 5

source = """
z = x + y
print(z)
"""

exec(source)

In this example, we define two variables x and y, and then assign a multi-line string to the source variable that contains Python code to be executed. We then call exec() with source, which executes the code in the string. The code creates a new variable z and prints its value, which is 15. The output of the code is 15.

Note that using exec() can be dangerous if the code being executed comes from an untrusted source, as it can potentially execute arbitrary code. It is generally recommended to avoid using exec() with untrusted input.