ADVERTISEMENT
ADVERTISEMENT

Python program to execute Python code from the string

Here, we have a string containing a block of code. We need to write a Python program to execute this Python code from the string.
Submitted by Shivang Yadav, on April 24, 2021

Python programming language is a high-level and object-oriented programming language. Python is an easy to learn, powerful high-level programming language. It has a simple but effective approach to object-oriented programming.

Strings in Python are immutable means they cannot be changed once defined.

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.

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

Python String Programs »



ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.