Python program to execute python code from a string
We have a block of code stored in a string and we will write a python program to execute this string's code.
Example:
Input string:
codeStr = """
print("Hello! Running python code from string")
a = 43
b = 3
print(a%b)
"""
Output:
Hello! Running python code from string
1
Python provides a function for executing the code that is stored inside a variable. The exec() function does the job in Python.
Syntax:
exec(code_string)
It takes in the string which contains the code.
Program to execute Python code from a string
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer