Executing String Code Using exec()
In this section, we will demonstrate how to execute Python code stored in a string using the built-in exec()
function.
Example 1: Using the Built-in exec()
Method
def exec_code(): # Defining code as a string LOC = """ def factorial(num): fact = 1 for i in range(1, num + 1): fact = fact * i return fact # Printing the factorial of 5 print(factorial(5)) """ # Executing the string code using exec() exec(LOC) # Call the function to execute the code exec_code()
Output:
120
In this example, the string contains the definition of a function that calculates the factorial of a number. When exec()
is called, it executes this code as if it were written directly in the script.
This is useful for dynamically running Python code from a string.