第八節:python函數

來源:互聯網
上載者:User

標籤:python   import   mingzi   hello   world   

python個人筆記,方便查詢,與侵權無關。

函數的定義:def test():    print "hello world!"test()     #調用上面的test函數 定義一個參數為name的函數:def mingzi(name):    print "hello %s,how old are you?"%namemingzi(‘darren‘)         #調用定義的函數定義兩個參數的函數:def info(name,age):    print "%s,%s"%(name,age)info(‘darren‘,‘23‘)         #調用兩個參數的函數給函數添加一個協助文檔:def mingzi(name):    ‘this is a help doc!‘    print "hello %s,how old are you?"%namen="darren"mingzi(n)     #也可以先賦值再調用函數>>>import tab>>>import three>>>help(three.mingzi)     #查看自己編寫的協助文檔 局部變數和全域變數:局部變數:函數執行結束以後會失去作用。def info (name):    age=22    print ‘your name is %s,you old is %s‘%(name,age)info(‘darren‘) 全域變數:在函數之外,全域生效。age=26def info (name):    age=22    print ‘your name is %s,you old is %s‘%(name,age)info(‘darren‘) 聲明把全域變數變為局部變數(不建議使用):age=26def info (name):    global age           #聲明    age=22    print ‘your name is %s,you old is %s‘%(name,age)info(‘darren‘)  print ‘age:‘,age         #此處第一個age:是顯示age:並不是變數,後面的才是變數,這是讓一個print產生兩段內容的用法。函數的預設參數: def users(username,group=‘iphone‘):          #group=‘iphone‘這裡也是一個賦值變數,只不過如果不賦值,預設是iphone。    list={}        #定義一個字典    list[username]=group        #定義username為key,group為value,意思就是修改key的值為變數group    return listprint users(‘wang‘)print users(‘wangjia‘,"dongge") 多預設值變數:def info (name,age,internation=‘zhongguo‘,provice=‘shandong‘):    age=22    print ‘your name is %s,you old is %s‘%(name,age)    print internation,proviceinfo(‘darren‘,‘age‘,provice=‘beijing‘,internation=‘meiguo‘)    #預設賦值的變數可以沒有順序,但是無預設值的變數必須在有預設值得變數的前面。函數的關鍵參數:def fun(a,b=5,c=10):    print a,b,cfun(3,7)fun(25,c=24)fun(c=50,a=100)  #重點:函數增加一個特殊參數,可以任意賦多個值。def test(*.args):    print argstest(‘darren‘,‘wang‘,‘29‘)#把一個字典賦值給函數,字典key對應的值就是變數。def testa (**kargs):    print kargsname_list={‘name‘=‘wang‘,‘age‘=‘22‘,‘iphone‘=‘pingguo‘}testa(name=‘darren‘,age=‘18‘,iphone=‘sanxing‘)#有時候我們希望能把函數執行的結果儲存下來,這時候就需要return參數:def users(username,group=‘iphone‘):      list={}         list[username]=group        return listyonghu=users(‘wang‘,‘group=‘linux‘)print yonghu lambda匿名函數:>>> a=lambda x:x+2>>> a(2)4-------a=range(10)map(lambda x:x**2,a)--------def f(x):        return x**2print f(4)普通函數和下面lambda函數相同g=lambda x:x**2print g(4) ----------


本文出自 “小東哥” 部落格,謝絕轉載!

第八節: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.