Python global variables and local variables

Source: Internet
Author: User
Tags variable scope

In python, the variable scope rules are somewhat different. In programming languages such as C/C ++ and java, global variables defined outside the function can be directly accessed within the function by default, however, this problem may occur in python. The following is an example.

Test. py :#! /Usr/bin/pythonCOUNT = 1def func (): COUNT = COUNT ++ 1 func () Python test. py, the system will run the error Traceback (most recent call last): File "test. py ", line 8, in
 
  
Func () File "test. py", line 6, in func COUNT = COUNT ++ 1 UnboundLocalError: local variable 'Count' referenced before assignment
 
"UnboundLocalError: local variable 'Count' referenced before assignment" means that the variable COUNT is referenced before the value is assigned.

Python is different from other programming languages. For programming languages such as C/C ++, the variable name actually represents a memory area.Place the new value in the memory area specified by the variable.. For python, all the variables are references to the memory area, and the value assigned to the variables is equivalentChange the memory referenced by the variable from one region to the other region where the new value is stored.. That is to say, in C/C ++, the correspondence between the variable name and the memory area does not change, but only the values stored in the corresponding memory. in python, A variable is only a reference to the memory region where the value is stored. The variable value is not changed because the value in the memory region pointed to by the variable has changed, instead, the variable references the memory area where new values are stored. All the variables in python are equivalent to the immutable variables in java. Any change in the value corresponds to the change in the variable reference memory region. The difference is as follows:


Figure 1 Comparison of Variables

In python, there is an id function. In python, there is an id function, and help (id) can see its description, as follows:

Help on built-in function id in module __builtin__:id(...)    id(object) -> integer        Return the identity of an object.  This is guaranteed to be unique among simultaneously existing objects.(Hint: it's the object's memory address.)(END)
To put it simply, the id function reflects the memory address of the object. See the following experiment results:
Test. py :#! /Usr/bin/pythonCOUNT = 1 for I in range (5): COUNT = COUNT + 1 print id (COUNT) python test. py running result: 1103132811031304110312801103125611031232
This is consistent with the figure above. Every value assignment in python changes the memory space referenced by the variable.

Back to the above error "referenced before assignment", this error occurs because python finds that the value of the COUNT variable in the function will be added to the local namespace of the function (in fact, this occurs before the function runs to the value assignment operation ). When the value assignment operation is performed, the COUNT variable is referenced on the right of the value assignment operator. In this case, the COUNT variable is only added to the local namespace of the function and is not assigned a specific value, so the above error will occur. In fact, the problem lies in the assignment operation, because the assignment operation causes the variable to be added to the local namespace of the function. If no value is assigned, but the variable is referenced, there is no problem, as shown below:

Test. py :#! /Usr/bin/pythonCOUNT = 1def func (): temp = COUNT + 1 print "temp:", COUNT print "COUNT:", COUNTfunc () python test. py running result: temp: 1 COUNT: 1
In this way, the COUNT variable is not added to the local namespace of the function, and the python interpreter does not find it in the local namespace of the function. Then, the python interpreter will continue searching in the global namespace. The result is that the COUNT definition is found in the global namespace and its value is referenced. Therefore, the program runs smoothly.

At this point, you may ask, can't you modify the value of a global variable in a function? No. If you want to modify the value of a global variable in the function, you must make a global declaration of the variable in the function to inform the python interpreter that the variable is in the global namespace, as shown below:

Test. py :#! /Usr/bin/pythonCOUNT = 1def func (): global COUNT = COUNT + 1 print "COUNT:", COUNTfunc () python test. py running result: COUNT: 2
OK. pai_^

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.