Q:

Python program to execute Python code from the string

belongs to collection: Python String Programs

0

Python program to execute python code from a string

We have a block of code stored in a string and we will write a python program to execute this string's code.

Example:

Input string:

codeStr = """ 
print("Hello! Running python code from string")
a = 43
b = 3
print(a%b)	
"""

Output:
Hello! Running python code from string
1

Python provides a function for executing the code that is stored inside a variable. The exec() function does the job in Python.

Syntax:

exec(code_string)

It takes in the string which contains the code.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to execute Python code from a string

# Python program to execute Python code 
# from a string

# string consisting of code 
codeStr = """print("Hello! Running python code from string")
a = 43
b = 3
print(a/b)"""	

# executing the code from string 
exec(codeStr)

Output:

Hello! Running python code from string
14.333333333333334

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to find uncommon words from two str... >>
<< Python program to check whether a given string is ...