引數------ 收集引數 *引數名
def
stu(
*info)
:print
(info[0]
)print
(info[1]
)print
(len
(info)
)print
(type
(info)
)stu(
'shanxi'
,'200008966',19
)
列印結果
shanxi
200008966
3<
class
'tuple'
>
返回值
def
stu():
return0,
'shanxi',50
print
(stu(
))
列印結果
(0,
'shanxi',50
)
可見如果返回多個值,python將其打包成元組
全域性變數問題,global關鍵字
當想要在自定義函式中使用全域性變數,就必須在變數前加global關鍵字,如果不加,python預設在函式內部新建乙個同名的區域性變數,當修改這個變數的值時,並不會影響全域性變數的值
看下面例子
count =
10def
stu():
count =
20print
(count)
stu(
)print
(count)
執行結果
10
10
如果加上global關鍵字
先宣告
count =
10def
stu():
global count #這裡
count =
20print
(count)
stu(
)print
(count)
執行結果
10
20
函式巢狀函式
count =
10def
fun1()
:print
('fun1正在呼叫.....'
)def
fun2()
:print
('fun2正在呼叫,,,,,'
) fun2(
)fun1(
)
執行結果
fun1正在呼叫...
..fun2正在呼叫,,,,,
閉包
下面這個我還沒搞懂幹啥的
def
fun1
(x):
deffun2
(y):
return x * y
return fun2
i = fun1(1)
print
(i)print
(type
(i))
print
(i(5))
print
('....................'
)print
(fun1(1)
(5))
執行結果
<
locals
>
.fun2 at 0x000001ebcdab41f8
>
<
class
'function'
>5.
....
....
....
....
...5
下面是錯誤例子
def
fun1()
: x =
5def
fun2()
: x *= x
return x
# 因為這裡又變成區域性變數了,所以會報錯
return fun2(
)i = fun1(
)
執行結果
traceback (most recent call last)
: file "e:/python project/test09_14/test.py"
, line 10,in
i = fun1(
) file "e:/python project/test09_14/test.py"
, line 7
,in fun1
return fun2(
) file "e:/python project/test09_14/test.py"
, line 4
,in fun2
x *= x
unboundlocalerror: local variable 'x' referenced before assignment
但是如果將x換成列表就不會報錯
def
fun1()
: x =[6
,3,5
]def
fun2()
: x[0]
*= x[0]
return x[0]
# 因為這裡又變成區域性變數了,所以會報錯
return fun2(
)i = fun1(
)print
(i)
執行結果
9
那接下來就引出了nonlocal
小夥伴覺得為什麼非得用列表,我就想用普通變數啊,
那看下面方法
def
fun1()
: x =
6def
fun2()
:nonlocal x
x *= x
return x
# 因為這裡又變成區域性變數了,所以會報錯
return fun2(
)i = fun1(
)print
(i)
執行結果
36
python之閉包函式
def closure conf prefix def innerfunc name print prefix,name return innerfunc holiday closure conf 10月1日是 holiday 國慶節 print function name is holiday.n...
python函式閉包和遞迴 函式和閉包之尾遞迴
前面提到過,如果想把更新var的while迴圈轉換成僅使用val這種更函式式的風格的話,有時候你可以使用遞迴。下面的例子是通過不斷改善猜測數字來逼近乙個值的遞迴函式 var guess initialguess while isgoodenough guess guess improve guess...
python閉包函式
python函式閉包 closure 比較抽象,在函式式程式設計中運用地比較多,通俗點就是子函式 內嵌函式 呼叫上層函式 閉包函式 的變數,且上層函式 閉包函式 接收的變數會儲存在子函式 內嵌函式 的變數中可以供子函式 內嵌函式 呼叫 概念很抽象,但是實現的例子還是比較容易理解的,這裡記住實現函式閉...