Given few lines of code inside a string variable and execute the code inside the string.
Input: code = """ a = 6+5 print(a)""" Output: 11 Explanation: Mind it that "code" is a variable and not python code. It contains another code, which we need to execute. Input: code = """ def factorial(num): for i in range(1,num+1): fact = fact*i return fact print(factorial(5))""" Output: 120 Explanation: On executing the program cantoning the variable in Python we must get the result after executing the content of the variable.
Here we use the exec() function to solve the code contained inside a variable. exec() function is used for the dynamic execution of Python code. It can take a block of code containing Python statements like loops, class, function/method definitions and even try/except block. This function doesn’t return anything. The code below solves the problem and explains the exec() function.
This article is contributed by Chinmoy Lenka. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Python code to move spaces to front of string in single traversal
- Python | Execute and parse Linux commands
- Python subprocess module to execute programs written in different languages
- Code Golfing in Python
- Issues with using C code in Python | Set 1
- Python code to convert SOP to POS
- Issues with using C code in Python | Set 2
- Code introspection in Python
- How to run Python code on Google Colaboratory
- Morse Code Translator In Python
- Hamming Code implementation in Python
- Python code formatting using Black
- Different Python IDEs and Code Editors
- Packaging and Publishing Python code
- Optimization Tips for Python Code