Beginner python, using version 3.6.
In doing a little exercise, you need to define a global variable in a local function (I understand that this is clumsy and practically meaningless). So I wrote a statement like the following:
Def func ():
a=input (' the name of ur var ')
exec (' Global ' +str (a) + ' =[] ')
Or a statement like this:
Def func ():
a=input (' the name of ur var ')
exec (' Global ' +str (a))
exec (' str (a) + ' =[] ')
Such......
These ' functions ' without exception, nothing happens when you run and enter a.
After a period of baffled, I chose to study online and read the Python documentation. Finally I found the answer:
In the programmer's recommendations below global statement, the following are described:
Programmer ' s Note: The global is a directive to the parser. It applies only to code parsed at the same time as Theglobal statement. In particular, Aglobal statement contained into a string or code object supplied to the built-inexec () function does not aff ECT The code blockcontaining the function call, and code contained in such a string is unaffected Byglobal statements in T He-code containing the function call. The same applies to Theeval () Andcompile () functions.
That's clear enough, then go to the EXEC () Description:
Programmer ' s hints: dynamic evaluation of expressions is supported by Thebuilt-in Functioneval (). The built-in functionsglobals () Andlocals () return to the current global and local dictionary Respectively,which UL to pass around for use Byexec.
It is explained that there is a problem of using the interpreter in the same time (personal understanding, welcome correction), so it will not work at the same time, so it will not raise the error.
Finally, if you are determined to achieve this wonderful function, it is also very good to do. You just need to call the Globals () dictionary in a function, such as the program can write:
Def func ():
a=input (' the name of ur var ')
globals () [Str (a)]=[]
The desired function can be achieved perfectly.
Of course, for programming reasons, if you really want to have this kind of demand, it is in the local operation to change the database in the global. It is better to define a dictionary and then operate the global dictionary in local functions in accordance with the usual practice.