Two solutions for implementing global variables in Python

Source: Internet
Author: User

The following describes how to implement global variables in Python:
Let's take a look at the following test procedure:

Count = 0def Fuc (count): print count + = 1for I in range (0, 10): Fuc (count)

The running result is:

>>> 0000000000

Obviously, this is not the result we want.

The solution to this problem is to use global variables:

Global aa = 3def Fuc (): global a print a = a + 1if _ name _ = "_ main __": global a for I in range (10): Fuc () print 'hello' print

The running result is:

>>> 3456789101112hello13

NOTE: If global variables are needed, declare them. However, do not pass parameters in a function. For example, Fuc (a) cannot be used.

Solution 2 -- list:

The sample code is as follows:

A = [3] def Fuc (): print a [0] a [0] = a [0] + 1if _ name _ = "_ main _": global a for I in range (10): Fuc () print 'hello' print a [0]

The result is the same as above.

The list can also be relatively simple to implement this function

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.