1. 程式人生 > >python變量作用域,函數與傳參

python變量作用域,函數與傳參

printf last 輸出 引用 error module str color 變量引用

一、元組傳值:

一般情況下函數傳遞參數是1對1,這裏x,y是2個參數,按道理要傳2個參數,如果直接傳遞元祖,其實是傳遞一個參數

>>> def show( x, y ):
...     print x, y
... 
>>> a = ( 10, 20 )
>>> show( a, 100 )
(10, 20) 100

而如果要把一個元祖( 有2項 )傳給x和y,傳遞的時候要用*a,如果一個函數要3個參數,就不能傳遞2項的元祖

>>> def show( x, y ):
...     print "%s : %s
" % ( x, y ) ... >>> a=(10,20) >>> show(*a) 10 : 20 >>> b=(10,20,30) >>> show(*b) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: show() takes exactly 2 arguments (3 given)
print "%s : %s" % ( x, y )

這個百分號%s 類似c語言的printf,占位符 表示要用一個字符串來解釋,後面的% ( x, y ) 就是傳值. x傳給第一個%s, y傳給第二個%s

如果後面不傳值,就是打印字符串本身

>>> print "%s : %s" % ( hello, ghostwu )
hello : ghostwu
>>> print "%s : %s"
%s : %s

二、變量作用域跟javascript一樣

函數外面定義的是全局變量,可以在函數裏面或者外面訪問

函數裏面定義的是局部變量,函數調用完畢之後會被釋放

>>> myname = ghostwu
>>> def show():
...     print myname
...     x 
= 10 ... >>> show() ghostwu >>> x Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name x is not defined >>> myname ghostwu >>>

global關鍵字可以把局部變量變成全局變量,這點跟php不一樣(php是把全局變量引用到函數內部使用)

>>> def show():
...     global a
...     a = 10
... 
>>> show()
>>> a
10

同名的全局變量和局部變量,函數內訪問的是局部變量,外面是全局變量

>>> a = 100
>>> def show():
...     a = 10
...     print a
... 
>>> a
100
>>> show()
10
>>> a
100

如果,同名的局部變量被global,並且函數被執行,那麽函數執行之後 在輸出這個變量,就是局部變量中的值

>>> a = 1
>>> def show():
...     global a
...     a = 2
... 
>>> a
1
>>> show()
>>> a
2

python變量作用域,函數與傳參