How do I execute a string containing Python code in Python?


In this article, we are going to find out how to execute a string containing Python code in Python.

To execute a string containing Python code we should take the input string as multi-line input using triple quotes, then we will use the inbuilt function exec(). This will take a string as input and returns the output of the code that is present inside the string.

The exec() function is used to execute Python programmes dynamically. These programmes can be either strings or object code. If it's a string, it's translated into a series of Python statements that are then performed, barring any syntax errors; if it's object code, it's just executed.

We must be careful not to utilise return statements anywhere other than within the declaration of a function, not even in the context of code that is passed to the exec() method.

Example

In the program given below, we are taking a multi-line coded string as input and we are finding out the output of that using the exec() method 

str1 = """

a = 3
b = 6
res = a + b

print(res)
"""

print("The output of the code present in the string is ")
print(exec(str1))

Output

The output of the above example is as shown below −

The output of the code present in the string is
9
None

Using eval() function

To execute an expression that is present inside a string, we will use the inbuilt function eval() and pass the string to the function and the output of the code present inside the string is returned.

Example

In the example given below, we are taking an expression as a string as an input and we are evaluating it using eval() method −

str1 = "3 + 5"

print("The output of the code present in the string is ")
print(eval(str1))

Output

The output of the above example is given below −

The output of the code present in the string is
8

Updated on: 07-Dec-2022

14K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements