1. 程式人生 > >python之global關鍵字

python之global關鍵字

例子如下:

def fun(x1,y):
	global y

	t=x1
	x1=y
	y=t



if __name__=="__main__":
         x=0
        
         y=1
        fun(x,y)
        
        print(x,y)

執行結果如下;
在這裡插入圖片描述

這裡有個錯誤,y是引數又是全域性的

找了好久,在這裡找到了
https://stackoverflow.com/questions/18807749/name-x-is-parameter-and-global-python

這是因為

全域性語句中列出的名稱不能定義為形式引數,也不能定義為 for迴圈控制目標,類定義,函式定義或import語句。

把global y 放到函式外面定義就行了或者把引數改為y1

def fun(x1,y1):
    global y
    t=x
    x1=y1
    y=t


x=0
y=1

fun(x,y)

print(x,y)

在這裡插入圖片描述