Originally intended to use the Eval function to assign a value to the variable, did not expect the invalid syntax error occurred. The source code is as follows
In [2]: eval (' a = 1 ') of File "<string>", line 1 a = 1 ^syntaxerror:invalid syntax
Baidu did not Baidu to the result, finally found a good answer on the StackOverflow, here is the original link.
The author means that theeval function is only responsible for processing the expression , and there is no function to assign a value, that is, the Eval function is only responsible for outputting your input, true or false, or something. However, it does not have the ability to affect the current code environment. the EXEC () function should be used if we want to use the assignment . Look at the code:
In [3]: exec (' a = 1 ') in [4]: aout[4]: 1
The solution to the problem has been given, so let's look at the official documentation for the two functions.
eval (expression, Global=none, Local=none)
The parameters are string and optional global and local. Global should be a dictionary file, and local should be a mapping object.
The expression parameter will be processed as a python (strictly speaking, a list of conditional statements), and the global and local parameters will be used as both globally and locally as namespaces.
EXEC (Object[,global,[locals])
This function can provide Python with dynamic code execution capabilities.
See, the official description of its function is so different, interested students can go to see more detailed documents ~ More detailed points here
Python Notes-Invalid syntax error calling eval function