InterviewSolution
| 1. |
What is the difference between built-in functions eval() and exec()? |
|
Answer» The eval() function evaluates a single expression embedded in a string. The exec() function on the other hand RUNS the script embedded in a string. There may be more than one Python statement in the string. Simple example of eval(): >>> x=5 >>> sqr=eval('x**2') >>> sqr 25Simple example of exec() >>> code=''' x=int(INPUT('ENTER a number')) sqr=x**2 print (sqr) ''' >>> exec(code) enter a number5 25eval() always RETURNS the RESULT of evaluation of expression or raises an error if the expression is incorrect. There is no return value of exec() function as it just runs the script. Use of eval() may pose a security risk especially if user input is accepted through string expression, as any harmful code may be input by the user. Both eval() and exec() functions can perform operations on a code object returned by another built-in function compile(). Depending on mode parameter to this function, the code object is prepared for evaluation or execution. |
|