How to execute a string of code in Python

Hello everyone, in this tutorial, we will learn how to execute a string of code in Python. As input, we will give a string which will be a piece of Python code. Our aim is to execute this code and get the desired result. See how it is done.

Let’s say we want to execute the following Python code.

for i in range(20):
    if (i%3 == 0):
        print(i)

This will print all the numbers divisible by 3 between 0 to 20.

0
3
6
9
12
15
18

Now if our input string contains this code, then to execute the string containing the code we first store the string in a variable using single or double-quotes as we do with normal strings. For a multiline code, we need to use 3 single or double-quotes. Then we pass it in the built-in function exec() as shown in the given example program. This function does not return anything. To read more on exec() function, read this article: Difference between Eval() and Exec() functions in Python

See the code implementation below.

code = '''
for i in range(20):
    if (i%3 == 0):
        print(i)
        '''
exec(code)

The above program gives the same output as the previous one. See here.

0
3
6
9
12
15
18

Note that indentation must be done properly for the string of code.

As you can notice this trick can be very useful when we want to execute a large string of Python code in our program.

Thank you.

Leave a Reply

Your email address will not be published. Required fields are marked *