Signup/Sign In
PUBLISHED ON: JULY 5, 2021

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.

Input:

"sum=5+4

print(a)"

Output: 9

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.

Algorithm

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

Python Program

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

def execute_code():
    Code="""
def check_prime_no(num):
  for i in range(2, num):
     if (num % i) == 0:
        return "Not Prime" 
     else:
        return "Prime"
print(check_prime_no(12)) """

    exec(Code)

execute_code()


Not Prime

Conclusion

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.



About the author:
Nikita Pandey is a talented author and expert in programming languages such as C, C++, and Java. Her writing is informative, engaging, and offers practical insights and tips for programmers at all levels.