In python, you must use the global keyword to declare global variables. Otherwise, problems may occur. For example, if a piece of code is like this, python will report an error.
#! /Usr/bin/python <br/> # filename: use_global.py <br/> # Author: Boyce <br/> # Email: boyce.ywr@gmail.com <br/> CNT = 0 <br/> def fun (): <br/> CNT + = 1 <br/> pass <br/> for I in range (0, 10): <br/> fun () <br/> Print CN
The error message is:
Traceback (most recent call last ):
File "use_global.py", line 13, in <module>
Fun ()
File "use_global.py", line 9, in fun
CNT + = 1
Unboundlocalerror: local variable 'cnt 'referenced before assignment
It means that the local variable CNT is not allocated before the reference, which is equivalent to assigning a value to an unspecified local variable in C. The reason is that, unlike the C language, a variable with the same name is declared in the local scope. It will generate a new local variable instead of using an external variable, because it is not like the C language int; A = 4 defines and references. Here, the CNT in fun is a local variable of fun, not the same as the CNT outside.
If you want to operate the CNT on the external side, you need to use the global keyword to declare that the global variable CNT is used instead of allocating a new CNT variable in fun.
#! /Usr/bin/python <br/> # filename: use_global.py <br/> # Author: Boyce <br/> # Email: boyce.ywr@gmail.com <br/> global CNT <br/> CNT = 0 <br/> def fun (): <br/> global CNT <br/> CNT + = 1 <br/> pass <br/> for I in range (0, 10): <br/> fun () <br/> Print CN
Execution result: 10