例1:
a = 100 #定義全局變量a
def test1():
print(a) #此處a為全局變量
def test2(a):#此處a為局部變量
print(a)#此處a為局部變量
test1() #結果為100
test2(3) #結果為3
例2:
1 temperature = 0
2
3 def get_temperature():
4 global temperature #在函數內部修改全局變量的值,要先用global聲明全局變量。
5 temperature = 33 #若不用global聲明就改值,對全局變量不起作用,只是作為局部變量使用
6
7 def print_temperature():
8 print('溫度是%d'%temperature) #在函數內部可直接引用全局變量的值,而不必聲明。
9
10 get_temperature()
11 print_temperature()
例3:.列表、字典 在函數中不用加global,也可以用作全局變量
1 t = [11,22,33]
2
3 def add_t():
4 t.append(44)
5 def print_t():
6 print(t)
7
8 add_t()
9 print_t() #結果為[11,22,33,44]