python基礎-函數

來源:互聯網
上載者:User

標籤: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基礎-函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.