python-2函數

來源:互聯網
上載者:User

標籤:abs   UI   bool   自訂   bsp   3.3   調用   The   www.   

http://docs.python.org/3/library/functions.html 或者菜鳥中文資料

1-使用函數

abs(-20)#求絕對值max(1,4,200,3,2) #求最大的值int(12.34) #轉成intfloat("12.34") #轉成floatstr(1.23) #轉成字串bool(1) #轉成bool類型bool(‘‘) 

 2-自訂函數

def my_abs(x):    if not isinstance(x, (int, float)):        return 222    if x >= 0:        return x    else:        return -x

  x,y=(111,222);  x值是111,y值是222. 函數可直接返回tuple函數

3-函數的參數

  3.1 預設參數, 定義預設參數要牢記一點:預設參數必須指向不變對象!

def sum(x, n=2):     return x+nsum(5)#相當於調用power(5, 2):def enroll(name, gender, age=6, city=‘Beijing‘):    print(‘city:‘, city)enroll(‘Adam‘, ‘M‘, city=‘Tianjin‘) #可以只傳指定參數

   

3.2 可變參數

def calc(*numbers): #*表示可變    sum = 0    for n in numbers:        sum = sum + n * n    return sumcalc(1,2,3) #參數調用nums=[1,2,3]calc(*nums) #第二種方式

 3.3 關鍵字參數

def person(name, age, **kw):    print(‘name:‘, name, ‘age:‘, age, ‘other:‘, kw)    extra = {‘city‘: ‘Beijing‘, ‘job‘: ‘Engineer‘}person(‘Jack‘, 24, **extra)

 3.4命名關鍵字參數

def person(name, age, *args, city=‘beijing‘, job):    print(name, age, args, city, job)person(‘xiaofeng‘,12,city=‘shenzhin‘,job=‘myjob‘)        extra = {‘city‘: ‘Beijing‘, ‘job‘: ‘Engineer‘}person(‘xiaofeng‘,12,**extra)

 

3.5參數組合

def f1(a, b, c=0, *args, **kw):    print(‘a =‘, a, ‘b =‘, b, ‘c =‘, c, ‘args =‘, args, ‘kw =‘, kw)    args = (1, 2, 3, 4)kw = {‘d‘: 99, ‘x‘: ‘#‘}f1(*args, **kw) #a = 1 b = 2 c = 3 args = (4,) kw = {‘d‘: 99, ‘x‘: ‘#‘}

 

python-2函數

聯繫我們

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