Program to execute python code and print the result

by | Mar 19, 2021 | Python Programs

Home » Python » Python Programs » Program to execute python code and print the result

Introduction

The task is to execute the python code placed inside the string variable and print the output.

Python gives us the flexibility to run our code inside the code i.e. dynamic execution of code. For this we have exec() function given by python.

Program to execute python code and print the result

Program

def exec_pycode():
    LOC = """
def sq(x):
    mul = x*x
    return mul
print(sq(5))
"""


#Execute python function
    exec(LOC)
exec_pycode()

 

Output

Program to execute python code and print the result Output

Explanation

In the above code, we have placed the python code inside the variable LOC and passed it as the argument to exec() function. The output of inside python code after execution is stored in variable LOC and displayed on the screen using print function.

Author

0 Comments

Submit a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author