Python global variables

Source: Internet
Author: User
Global variables do not conform to the spirit of parameter passing. Therefore, I seldom use them unless a constant is defined. Today, when a colleague asked a question about global variables, he found that there were still internal global variables that do not conform to the spirit of parameter transfer. Therefore, I rarely use them unless I define constants. Today, a colleague asked a question about global variables and found that there was still a portal.

The program is roughly like this:

CONSTANT = 0def modifyConstant() :        print CONSTANT        CONSTANT += 1        returnif __name__ == '__main__' :        modifyConstant()        print CONSTANT

The running result is as follows:

UnboundLocalError: local variable 'constant' referenced before assignment

It seems that the global variable is a local variable in the modifyConstant function. does it seem that the global variable has not taken effect?

Modify:

CONSTANT = 0def modifyConstant() :        print CONSTANT        #CONSTANT += 1        returnif __name__ == '__main__' :        modifyConstant()        print CONSTANT

It seems that the function can access global variables.

Therefore, the problem is that, because the variable CONSTANT is modified inside the function, Python considers CONSTANT as a local variable, and print CONSTANT is before CONSTANT + = 1, this error will certainly occur.

So, how should we access and modify global variables inside the function? You should use the keyword global to modify the variable (a bit like PHP ):

CONSTANT = 0def modifyConstant() :        global CONSTANT        print CONSTANT        CONSTANT += 1        returnif __name__ == '__main__' :        modifyConstant()        print CONSTANT

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.