1.

Built-in exec() function is provided for dynamic execution of Python code. Explain its usage.

Answer»

Python’s built-in function library contains exec() function that is useful when it comes to dynamic execution of Python code. The prototype syntax of the function is as follows:

exec(object, GLOBALS, locals)

The object parameter can be a string or code object. The globals and locals PARAMETERS are optional. If only globals is provided, it must be a dictionary, which will be used for both the global and the local variables. If both are given, they are used for the global and local variables, respectively. The locals can be any mapping object.

In first example of usage of exec(), we have a string that contains a Python script.

>>> string=''' x=int(input('enter a number')) y=int(input('enter another number')) print ('sum=',x+y) ''' >>> exec(string) enter a number2 enter another number4 sum= 6

Secondly, we have a Python script saved as example.py

#example.py x=int(input('enter a number')) y=int(input('enter another number')) print ('sum=',x+y)

The script FILE is read using built-in open() function as a string and then exec() function executes the code

>>> exec(open('example.py').read()) enter a NUMBER1 enter another number2 sum= 3

As a third example, the string containing Python code is first compiled to code object using compile() function

>>> string=''' x=int(input('enter a number')) y=int(input('enter another number')) print ('sum=',x+y) ''' >>> obj=compile(string,'example', 'exec') >>> exec(obj) enter a number1 enter another number2 sum= 3

Thus we can see how exec() function is useful for dynamic execution of Python code.



Discussion

No Comment Found