SoFunction
Updated on 2024-11-13

Python Execute String Expression Function (eval exec execfile)

Three functions were learned after careful study:
eval:Calculates an expression in a string.
exec:Execute the statement in the string.
execfile: Used to execute a file.

Note that exec is a statement, while eval() and execfile() are built-in built-in functions.

Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> x=1
>>> print eval("x+1")
2
>>> exec "print '/'"
/
>>> 

At the same time, we sometimes use input to enter some data, such as

>>> input("Please enter:")
Please enter:1+2**3
9
>>> 

In fact, the input here is also an application of eval, equivalent to the

>>> eval(raw_input("Please enter:"))
Please enter:1+2**3
9
>>>