一、函數定義,參數,以及傳回值
def 函數名():
函數體
傳回值:通過return函數
>>> def fun():
>>> def add(a,b):
print(a+b)
>>> add(34,78)
112
>>> def add1(a,b):
return a*b
>>> add1(12,5)
60
>>>
print('第一個函數')>>> fun()第一個函數>>> def fun(name):print("第二個函數"+name)>>> fun(age)Traceback (most recent call last): File "<pyshell#7>", line 1, in <module> fun(age)NameError: name 'age' is not defined>>> fun('age')第二個函數age
二、函數文檔
>>> def fun(name):
'函數定義過程的name是形參!'
#因為表示一個形式,标志占據一個位置
print('傳遞參數'+name+'是實參,有具體參數值')
>>> fun('xiao')
傳遞參數xiao是實參,有具體參數值
>>> fun._doc_
Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>
fun._doc_
>>> help(fun)
Help on function fun in module __main__:
fun(name)
函數定義過程的name是形參!
關鍵參數
>>> fun(name='關鍵參數')
傳遞參數關鍵參數是實參,有具體參數值
>>>
收集參數:
參數前加*
>>> def test(*param):
print("參數的長度是:",len(param))
print("第一個參數是:",param[1])
>>> test(1,2,3,4)
參數的長度是: 4
第一個參數是: 2
>>>
>>> def test(*param):
print("參數的長度是:",len(param))
print("第一個參數是:",param[1])
>>> test(1,2,3,4)
參數的長度是: 4
第一個參數是: 2
>>> def test1(*param,exp)
SyntaxError: invalid syntax
>>> def test1(*param,exp):
print("參數的長度是:",len(param))
print("第一個參數是:",param[1])
print('exp是:',exp)
>>> test1(1,2.3,4,exp="普通參數")
參數的長度是: 3
第一個參數是: 2.3
exp是: 普通參數
>>>
函數與過程:
函數有傳回值,python中隻有函數、、
全局變量和局部變量:
def discount(price,rate):
final_price=price*rate
return final_price
old_price=float(input("請輸入原價:"))
rate=float(input("請輸入折扣率:"))
new_price=discount(old_price,rate)
print("打折後的價格:",new_price)
内嵌函數和閉包:
>>> count=5 #全局變量
>>> def myfun():
count=10 #局部變量
print(10)
>>> myfun()
10
>>> print()count
SyntaxError: invalid syntax
>>> print(count)
5
>>>
全局變量用global申明:
>>> def myfun():
global count
count=10
print(count)
>>> nyfin()
Traceback (most recent call last):
File "<pyshell#63>", line 1, in <module>
nyfin()
NameError: name 'nyfin' is not defined
>>> myfun()
10
>>> print(count)
10
>>> count=1
>>> print(count)
1
>>> myfun(count)
Traceback (most recent call last):
File "<pyshell#69>", line 1, in <module>
myfun(count)
TypeError: myfun() takes 0 positional arguments but 1 was given
>>> myfun()
10
>>>