w3resource

Python Exercise: Execute a string containing Python code


Write a Python program to execute a string containing Python code.

Sample Solution:

Python Code:

# Define a string variable 'mycode' containing a Python code as a string
mycode = 'print("hello world")'

# Define a multi-line string variable 'code' containing Python code as a string
code = """
def mutiply(x,y):
    return x*y

print('Multiply of 2 and 3 is: ',mutiply(2,3))
"""

# Execute the Python code represented by the string stored in the variable 'mycode'
exec(mycode)

# Execute the Python code represented by the multi-line string stored in the variable 'code'
exec(code) 

Sample Output:

hello world                                                                                                   
Multiply of 2 and 3 is:  6  

Explanation:

In the exercise above the code utilizes the "exec()" function to execute Python code represented as strings ('mycode' and 'code'). It executes the Python code inside these strings, printing "hello world" using 'exec(mycode)' and defining a function "mutiply()" and performing a multiplication operation using 'exec(code)'.

Flowchart:

Flowchart: Python exercises: Execute a string containing Python code.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to make a chain of function decorators (bold, italic, underline etc.).
Next: Write a Python program to access a function inside a function.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.