Python Tutorial global variable usage

Source: Internet
Author: User
This example describes the Python global variable usage. Share to everyone for your reference, as follows:

Global variables do not conform to the spirit of parameter passing, so, usually I seldom use unless I define constants. Today, a colleague asked a question about global variables and found that there were doorways.

The procedure is broadly like this:

CONSTANT = 0def modifyconstant ():  print CONSTANT  CONSTANT + = 1  returnif __name__ = = ' __main__ ':  modifyc Onstant ()  print CONSTANT

The results of the operation are as follows:

Unboundlocalerror:local variable ' CONSTANT ' referenced before assignment

It appears that the global variable is a local variable in the function modifyconstant, and it seems that the global variable is not in effect?

Make some changes:

CONSTANT = 0def modifyconstant ():  print CONSTANT  #constant + = 1  returnif __name__ = = ' __main__ ':  Modify Constant ()  print Constant

Running normally, it seems that the function can access the global variables inside.

So, the problem is, because the variable Constant,python inside the function thinks constant is a local variable, and the print constant is before constant + = 1, so of course this error occurs.

So how do you access and modify global variables inside a 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__ = = ' __m Ain__ ':  modifyconstant ()  print CONSTANT

It's so easy!

More interested in Python related content readers can view this site topic: "Python Picture Operation skills Summary", "Python data structure and algorithm tutorial", "Python Socket Programming Skills Summary", "Python function Use Tips", " Python string manipulation Tips Summary, Python Introductory and Advanced classic tutorials, and Python file and directory operations tips

I hope this article is helpful for Python program design.

  • 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.