5-11 函數 賦值參數,可變參數

來源:互聯網
上載者:User

標籤:

函數

 

def sayHi():

    print ‘Hi‘

def cheng(a,b):

    return a*b

print cheng(3,4)

 

局部變數:函數內部定義,函數調用結束後釋放

全域變數:函數內外都可調用,global

>>> def hanshu2():
... global x                   #x為全域變數,x在函數內部加2的同時,全域變數x也改變了
... x=x+2
... print x

 

賦值參數 

def(x=1,y)                       #語法錯誤,賦值的參數後面不能有未賦值的參數,也就是賦值參數要放後面   

#練習

>>> def compare(a,b,c):  #找出最大值函數
... if a>=b:
... if a>=c: return a
... else: return c
... else:
... if b>=c: return b
... else: return c
...

 

文檔字串

>>> def wendang():
... ‘‘‘test doc function‘‘‘           #文檔字串
... print ‘hi‘
...
>>> wendang()
hi
>>> wendang.__doc__
‘test doc function‘
>>>

 

可變參數

# encoding:utf-8def he(x,*y):                      #*用來傳遞任意個無名字參數,這些參數會一個Tuple的形式訪問    ‘‘‘乘機之和的練習‘‘‘    total = 0    for i in y:        total = total + i*x    return totalprint he(3,4)print he(3,4,5)

 

# encoding:utf-8def canshu(**y):                                      # **用來處理傳遞任意個有名字的參數,這些參數用dict來訪問    print u‘輸入字典的長度為:%s‘ %(len(y))    print y    print y.keys()    print y.values()canshu(name=‘vp‘,age=‘m‘,sex=‘f‘)

 

5-11 函數 賦值參數,可變參數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.