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.
By Shivang Yadav Last updated : March 04, 2024

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

To understand the above program, you should have the basic knowledge of the following Python topics:

Python String Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.