Write A Python Function To Execute A String Containing Python Code

Provided a string as an input to the Python function,  the Python function should accept the string as an argument and execute the contents of the string.

In order to execute a string Python provide exec() function call


Write A Python Function To Execute A String Containing Python Code

 

 

Write A Python Function To Execute A String Containing Python Code

Let's define a function named execute_code(),  give the input argument as a string.  use the exec() function call to to execute the string

def execute_code(text):
   exec(text)





In the main program take some python code as string, Call the above code to execute the string.  As shown below

data = "print('hello world')"
execute_code(data)

 

 

Python code
===============

def execute_code(text):
   exec(text)

data = "print('hello world')"
execute_code(data)

 



OUTPUT
===============

hello world





Python code to print numbers 12345
=================================

def execute_code(text):
   exec(text)


data = "print(12345)"
execute_code(data)




OUTPUT
================

12345





Write A Python Function To Execute A String Containing Python Code

Ask the user to enter python code as an input to the program,  then pass the input string to the function and execute the python code.

Complete Program
==================

def execute_code(text):
  exec(text)


data = input("Enter a Python Code to Execute : ")
execute_code(data)





OUTPUT
===============

Enter a Python Code to Execute : if 1 < 2: print(2)
2




Conclusion
==================

Execute the program by yourself and provide the python code as an input to the program. Record the output.





Post a Comment

0 Comments