Python implements two solutions for global variables

  • 2020-04-02 13:48:43
  • OfStack

In this paper, the global variable implementation method for Python is summarized as follows:
Let's take a look at the following test procedure:


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

The running result is:


>>>
0
0
0
0
0
0
0
0
0
0

Obviously, this is not what we want.

The solution to this problem is to use global variables:


global a
a = 3
def Fuc():
  global a
  print a
  a = a + 1
if __name__ == "__main__":
  global a
  for i in range(10):
    Fuc()print 'hello'
  print a

The running result is:


>>>
3
4
5
6
7
8
9
10
11
12
hello
13

Note: where global variables are needed, declare them; However, don't send parameters to tens of millions of letters. For example, it is impossible to use Fuc(a).

Solution 2-- list:

The sample code is as follows:


a = [3]
def Fuc():
  print a[0]
  a[0] = a[0] + 1
if __name__ == "__main__":
  global a
  for i in range(10):
    Fuc()
  print 'hello'
  print a[0]

The same as above

Lists are also easier to implement


Related articles: