python 实现全局变量

时间:2021-10-08 10:28:37

1. 问题:

count = 0
def Fuc(count):
    print count
    count += 1

for i in range(0, 10):
    Fuc(count)

>>> 
0
0
0
0
0
0
0
0
0
0
2. 全局变量:

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

>>>
3
4
5
6
7
8
9
10
11
12
13
3. 借用列表来实现:

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]