99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁精彩閱讀Python基礎(chǔ)之函數(shù)用法實(shí)例詳解
Python基礎(chǔ)之函數(shù)用法實(shí)例詳解
2017-08-25
收藏

Python基礎(chǔ)之函數(shù)用法實(shí)例詳解

本文以實(shí)例形式較為詳細(xì)的講述了Python函數(shù)的用法,對(duì)于初學(xué)Python的朋友有不錯(cuò)的借鑒價(jià)值。分享給大家供大家參考之用。具體分析如下:

通常來說,Python的函數(shù)是由一個(gè)新的語句編寫,即def,def是可執(zhí)行的語句--函數(shù)并不存在,直到Python運(yùn)行了def后才存在。

函數(shù)是通過賦值傳遞的,參數(shù)通過賦值傳遞給函數(shù)

def語句將創(chuàng)建一個(gè)函數(shù)對(duì)象并將其賦值給一個(gè)變量名,def語句的一般格式如下:   

def <name>(arg1,arg2,arg3,……,argN):
 
  <statements>

def語句是實(shí)時(shí)執(zhí)行的,當(dāng)它運(yùn)行的時(shí)候,它創(chuàng)建并將一個(gè)新的函數(shù)對(duì)象賦值給一個(gè)變量名,Python所有的語句都是實(shí)時(shí)執(zhí)行的,沒有像獨(dú)立的編譯時(shí)間這樣的流程

由于是語句,def可以出現(xiàn)在任一語句可以出現(xiàn)的地方--甚至是嵌套在其他語句中:   
if test:
  def fun():
    ...
else:
  def func():
    ...
...
func()

可以將函數(shù)賦值給一個(gè)不同的變量名,并通過新的變量名進(jìn)行調(diào)用:
    
othername=func()
othername()

創(chuàng)建函數(shù)

內(nèi)建的callable函數(shù)可以用來判斷函數(shù)是否可調(diào)用:
    
>>> import math
>>> x=1
>>> y=math.sqrt
>>> callable(x)
False
>>> callable(y)
True

使用del語句定義函數(shù):    
>>> def hello(name):
    return 'Hello, '+name+'!'
>>> print hello('world')
Hello, world!
>>> print hello('Gumby')
Hello, Gumby!

編寫一個(gè)fibnacci數(shù)列函數(shù):
    
>>> def fibs(num):
     result=[0,1]
    for i in range(num-2):
       result.append(result[-2]+result[-1])
     return result
>>> fibs(10)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
>>> fibs(15)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]

在函數(shù)內(nèi)為參數(shù)賦值不會(huì)改變外部任何變量的值:
    
>>> def try_to_change(n):
    n='Mr.Gumby'
>>> name='Mrs.Entity'
>>> try_to_change(name)
>>> name
'Mrs.Entity'

由于字符串(以及元組和數(shù)字)是不可改變的,故做參數(shù)的時(shí)候也就不會(huì)改變,但是如果將可變的數(shù)據(jù)結(jié)構(gòu)如列表用作參數(shù)的時(shí)候會(huì)發(fā)生什么:    
>>> name='Mrs.Entity'
>>> try_to_change(name)
>>> name
'Mrs.Entity'
>>> def change(n):
     n[0]='Mr.Gumby'
 
>>> name=['Mrs.Entity','Mrs.Thing']
>>> change(name)
>>> name
['Mr.Gumby', 'Mrs.Thing']

參數(shù)發(fā)生了改變,這就是和前面例子的重要區(qū)別

以下不用函數(shù)再做一次:
    
>>> name=['Mrs.Entity','Mrs.Thing']
>>> n=name #再來一次,模擬傳參行為
>>> n[0]='Mr.Gumby' #改變列表
>>> name
['Mr.Gumby', 'Mrs.Thing']

當(dāng)2個(gè)變量同時(shí)引用一個(gè)列表的時(shí)候,它們的確是同時(shí)引用一個(gè)列表,想避免這種情況,可以復(fù)制一個(gè)列表的副本,當(dāng)在序列中做切片的時(shí)候,返回的切片總是一個(gè)副本,所以復(fù)制了整個(gè)列表的切片,將會(huì)得到一個(gè)副本:    
>>> names=['Mrs.Entity','Mrs.Thing']
>>> n=names[:]
>>> n is names
False
>>> n==names
True

此時(shí)改變n不會(huì)影響到names:    
>>> n[0]='Mr.Gumby'
>>> n
['Mr.Gumby', 'Mrs.Thing']
>>> names
['Mrs.Entity', 'Mrs.Thing']
>>> change(names[:])
>>> names
['Mrs.Entity', 'Mrs.Thing']

關(guān)鍵字參數(shù)和默認(rèn)值

參數(shù)的順序可以通過給參數(shù)提供參數(shù)的名字(但是參數(shù)名和值一定要對(duì)應(yīng)):    
>>> def hello(greeting, name):
    print '%s,%s!'%(greeting, name)
>>> hello(greeting='hello',name='world!')
hello,world!!

關(guān)鍵字參數(shù)最厲害的地方在于可以在參數(shù)中給參數(shù)提供默認(rèn)值:
    
>>> def hello_1(greeting='hello',name='world!'):
    print '%s,%s!'%(greeting,name)
 
>>> hello_1()
hello,world!!
>>> hello_1('Greetings')
Greetings,world!!
>>> hello_1('Greeting','universe')
Greeting,universe!

若想讓greeting使用默認(rèn)值:    
>>> hello_1(name='Gumby')
hello,Gumby!

可以給函數(shù)提供任意多的參數(shù),實(shí)現(xiàn)起來也不難:
    
>>> def print_params(*params):
     print params
 
>>> print_params('Testing')
('Testing',)
>>> print_params(1,2,3)
(1, 2, 3)

混合普通參數(shù):
    
>>> def print_params_2(title,*params):
     print title
     print params
 
>>> print_params_2('params:',1,2,3)
params:
(1, 2, 3)
>>> print_params_2('Nothing:')
Nothing:
()

 星號(hào)的意思就是“收集其余的位置參數(shù)”,如果不提供任何供收集的元素,params就是個(gè)空元組

但是不能處理關(guān)鍵字參數(shù):    
>>> print_params_2('Hmm...',something=42)
Traceback (most recent call last):
 File "<pyshell#112>", line 1, in <module>
  print_params_2('Hmm...',something=42)
TypeError: print_params_2() got an unexpected keyword argument 'something'

試試使用“**”:    
>>> def print_params(**params):
     print params
 
>>> print_params(x=1,y=2,z=3)
{'y': 2, 'x': 1, 'z': 3}
>>> def parames(x,y,z=3,*pospar,**keypar):
     print x,y,z
     print pospar
     print keypar
 
>>> parames(1,2,3,5,6,7,foo=1,bar=2)
1 2 3
(5, 6, 7)
{'foo': 1, 'bar': 2}
>>> parames(1,2)
1 2 3
()
{}
>>> def print_params_3(**params):
     print params
 
>>> print_params_3(x=1,y=2,z=3)
{'y': 2, 'x': 1, 'z': 3}
>>> #返回的是字典而不是元組
>>> #組合‘#'與'##'
>>> def print_params_4(x,y,z=3,*pospar,**keypar):
     print x,y,z
     print pospar
     print keypar
 
>>> print_params_4(1,2,3,5,6,7,foo=1,bar=2)
1 2 3
(5, 6, 7)
{'foo': 1, 'bar': 2}
>>> print_params_4(1,2)
1 2 3
()
{}
相信本文所述對(duì)大家Python程序設(shè)計(jì)的學(xué)習(xí)有一定的借鑒價(jià)值。

數(shù)據(jù)分析咨詢請(qǐng)掃描二維碼

若不方便掃碼,搜微信號(hào):CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機(jī)數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進(jìn)行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個(gè)參數(shù)驗(yàn)證碼對(duì)象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個(gè)配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺(tái)檢測極驗(yàn)服務(wù)器是否宕機(jī) new_captcha: data.new_captcha, // 用于宕機(jī)時(shí)表示是新驗(yàn)證碼的宕機(jī) product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說明請(qǐng)參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計(jì)時(shí)完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請(qǐng)輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請(qǐng)輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }