有同學還對python中的全局變量和局部變量分不清的,這裏有幾個案例來說明,可以看出,python2.x和3.x都是一樣的結果
代碼塊
# Python 2.7.13測試結果
>>> b = "outer"
>>> def func():
... global b # 聲明一個全局變量b
... b = "inner" # 全局變量b在此函數體內被修改爲inner
... print b # 打印的是inner
...
>>> func()
inner
>>> print b # 全局變量b在函數體內已被修改爲inner
inner
# python 3.5.1測試結果
>>> c = "CCC"
>>> def func_c():
... global c # 聲明一個全局變量c
... c = "test" # 全局變量c在此函數體內被修改爲test
... print(c) # 打印的是test
...
>>> func_c()
test
>>> print(c) # 全局變量c在函數體內已被修改爲test
test
>>> # 再來一個例子
>>> num = 10
>>> def hello():
num = 20
>>> def world():
print num
>>> world() # 爲什麼打印的是10?因爲world()函數中的num沒有定義,就會從上一級去找,最終找到了全局變量num=10
10
>>> hello() # hello()裏面的num是屬於hello()函數的局部變量,和外面的全局變量是不同的對象
>>> world() # world()函數裏的num沒在world函數中定義過,要想調用num就只能從上一級找,也就是全局的num=10
10
好了,就寫到這裏,看官們覺得漲知識了,請在文章左側點個贊 ^_^