The invalid syntax error occurs when calling the eval function in python study notes.
Pytho is free to use and distribute. It is an object-oriented language. Its Class module supports advanced concepts such as polymorphism, Operator overloading, and multi-inheritance. It is easy to use OOP with simple syntax and type unique to python. Python has many built-in pre-compiled and portable functional modules called the standard library ). Python can call libraries of C and C ++. It can be called by programs of C and C ++. It can be integrated with java components and can be integrated with COM and. and can interact with the network through interfaces such as SOAP, XML-RPC and CORBA, so python is not just an independent tool.
I wanted to use the eval function to assign values to the variables. I didn't expect the invalid syntax error to occur. The source code is as follows:
In [2]: eval('a = 1') File "<string>", line 1 a = 1 ^SyntaxError: invalid syntax
Baidu did not reach the result, and finally found a good answer on stackoverflow.
The author means that the eval function is only responsible for processing the expression and does not assign values. That is to say, the eval function is only responsible for outputting your input, true or False or something. However, it does not affect the current Code environment. If we want to assign values, we should use the exec () function. Check the Code:
In [3]: exec('a = 1')In [4]: aOut[4]: 1
The solution to the problem has been provided, so let's take a look at the official documentation for how these two functions are said.
Eval (expression, global = None, local = None)
Parameters are strings and optional global and local. Global should be a dictionary file, and local should be a ing object.
The expression parameter is processed as a python expression (strictly speaking, it is a string of conditional statements), and the global and local parameters are used as global and local namespaces.
Exec (object [, global, [locals])
This function can provide dynamic code execution for python.