標籤:none return 類型 變數 賦值 bsp 全域 nbsp pre
參數類型:
一、位置參數,必填參數
def file(file_neme,content):#形參,形式參數
f = open(file_neme,‘w‘)
f.write(content)
f.close()
file(‘lijun‘,‘qqqqqqq‘)#實參,實際參數
file(‘lijun‘,‘wwwwwww‘)
二、預設值參數,非必填參數,傳的話就用傳的參數,沒傳就用預設值
def file(file_neme,content=‘‘):#形參,形式參數
f = open(file_neme,‘a+‘)
f.write(content)
f.close()
file(‘lijun‘,‘qqqqqqq‘)#實參,實際參數
file(‘lijun‘)
多個參數時,可用以下兩種方式
三、可變參數,多餘的參數都會放到args裡,args是一個元組
def test(a,b=1,*args):#args名可以隨便起,一般情況都用args
print(‘a:‘,a)
print(‘b:‘,b)
print(‘args:‘,args)
print(args[0])
test(‘hahah‘,‘2‘,‘qqq‘,‘eee‘,‘444‘)#位置調用,b賦值2
test(a=‘hahah‘)#關鍵字調用
test(a=‘hahah‘,args="‘qqq‘,‘eee‘,‘444‘")#args不能用關鍵字調用,只能位置調用
四、關鍵字參數,kwargs是一個字典
def test(**kwargs):#kargs名可以隨便起,一般情況都用kwargs
print(kwargs)
test(name=‘hhh‘)#需要用字典的形式去傳參數
傳回值
如果想擷取函數結果,必須return
如果沒有寫retnrn,傳回值是None
return,函數立即結束
def file(file_neme,content=‘‘):#形參,形式參數
f = open(file_neme,‘a+‘)
if content:
f.write(content)
else:
f.seek(0)
res = f.read()
return res
f.close()
users=file(‘lijun‘,‘‘)#實參,實際參數
print(users)
全域變數、局部變數
a=100#全域
def test():
#a=5 #局部變數
print(‘裡面的‘,a)
test()
print(‘外面d‘,a)
如想修改全域變數,需先聲明global
a=100#全域
def test():
global a#聲明全域變數
a=5
print(‘裡面的‘,a)
test()
print(‘外面d‘,a)
python基礎-函數