Global variables of Python learning notes

Source: Internet
Author: User

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

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.