Python Program to execute a String of Code in Python
In this tutorial, we will learn to execute code given in a string format in Python. On executing the Python code which is given inside a string, we should get the result after executing the code as the output of our program.
Look at the examples to understand the input and output format.
To execute this problem, we will use the exec() method to run the code inside the string. It can take a block of code containing Python statements like loops, class, function/method definitions, and even try/except block. This function doesn’t return anything. To get the result, we will have to use the print() method.
Look at the algorithm to understand the approach better.
Step 1- Define a function to solve the problem
Step 2- Declare a variable with code as a string
Step 3- Use exec() and pass the variable which has a string
Step 4- Execute the function defined by us to run the code
In this program, we have defined a function that will execute the line of code given as a string. The code is of checking if a number is prime or not. In the program, we have checked if 12 is a prime number or not by giving the code for checking prime number as a string and then executing it using exec() method.
# use exec() to execute code in a string
for i in range(2, num):
if (num % i) == 0:
return "Not Prime"
Here, we have seen how to execute lines of code that are given in string format. To execute string we have used the exec() method. To know about exec() method in detail follow this guide.