Execute a line of code in Python

Loops | Python Methods and Functions | String Variables

Examples:

 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

# Python program illustrating the use of exec for
# execute this code as a string.

 
# a function that illustrates how exec () works.

def exec_code ():

LOC = "" "

def factorial (num):

  Fact = 1

  for i in the range (1, num + 1):

fact = fact * me

return fact

print (factorial (5))
"" "

exec (LOC)

 
Driver code
exec_code ()

Output:

 120 

This article courtesy of Chinma Lenka . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you'd like to share more information on the topic discussed above.