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

熱線電話:13121318867

登錄
首頁精彩閱讀詳解Python中的各種函數(shù)的使用
詳解Python中的各種函數(shù)的使用
2017-11-30
收藏

詳解Python中的各種函數(shù)的使用

函數(shù)是有組織的,可重復使用的代碼,用于執(zhí)行一個單一的,相關的動作的塊。函數(shù)為應用程序和代碼重用的高度提供了更好的模塊。

正如我們知道的,Python的print()等許多內置函數(shù),但也可以創(chuàng)建自己的函數(shù)。這些函數(shù)稱為用戶定義函數(shù)。
定義一個函數(shù)

可以定義函數(shù),以提供所需的功能。下面是簡單的規(guī)則來定義Python函數(shù)。
        函數(shù)塊以開始關鍵字def后跟函數(shù)名和括號中(())。
        任何輸入?yún)?shù)或參數(shù)應該放在這些括號內。還可以定義這些括號內的參數(shù)。
        函數(shù)的第一個語句可以是??一個可選的聲明 - 該函數(shù)或文檔字符串的文檔字符串。
        每個函數(shù)中的代碼塊以冒號(:)開頭并縮進。
        該語句返回[表達式]退出功能,可選地傳遞回一個表達式給調用者。不帶參數(shù)return語句返回None。
語法:    
def functionname( parameters ):
  "function_docstring"
  function_suite
  return [expression]

默認情況下,參數(shù)具有一個位置的行為和需要,它們被定義為通知他們以相同的順序。
例子:

這是最簡單的Python函數(shù)形式。這個函數(shù)接受一個字符串作為輸入?yún)?shù),并打印標準的屏幕上。    
def printme( str ):
  "This prints a passed string into this function"
  print str
  return

調用函數(shù)

定義一個函數(shù)只給出它的名稱,指定要被包括在功能和結構的代碼塊的參數(shù)。

一旦函數(shù)的基本結構確定后,可以通過從其他函數(shù)或直接從Python提示符調用它執(zhí)行它。以下是示例調用printme()函數(shù):
#!/usr/bin/python
 
# Function definition is here
def printme( str ):
  "This prints a passed string into this function"
  print str;
  return;
 
# Now you can call printme function
printme("I'm first call to user defined function!");
printme("Again second call to the same function");

當執(zhí)行上面的代碼中,產生以下結果:    
I'm first call to user defined function!
Again second call to the same function

引用VS值傳遞

所有參數(shù)(參數(shù))在Python語言是通過引用傳遞。這意味著,如果你在一個函數(shù)中改變了一個參數(shù)的值,變化也反映了在調用函數(shù)中。例如:    
#!/usr/bin/python
 
# Function definition is here
def changeme( mylist ):
  "This changes a passed list into this function"
  mylist.append([1,2,3,4]);
  print "Values inside the function: ", mylist
  return
 
# Now you can call changeme function
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist

這里,我們保持傳遞的對象的參考,并在同一個對象附加的值。這樣,這將產生以下結果:    
Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]

還有就是參數(shù)通過引用傳遞和引用被覆蓋在被調用的函數(shù)里面一個例子。    
#!/usr/bin/python
 
# Function definition is here
def changeme( mylist ):
  "This changes a passed list into this function"
  mylist = [1,2,3,4]; # This would assig new reference in mylist
  print "Values inside the function: ", mylist
  return
 
# Now you can call changeme function
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist

參數(shù)myList上局部函數(shù)changeme。更改函數(shù)內mylist不影響mylist。函數(shù)沒有作用,最后這會產生以下結果:    
Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]

函數(shù)參數(shù):

可以通過使用形參的類型如下調用函數(shù):

        必需的參數(shù)
        關鍵字參數(shù)
        默認參數(shù)
        可變長度參數(shù)

必需的參數(shù):

所需的參數(shù)為傳遞給正確的位置順序的函數(shù)的參數(shù)。這里,在函數(shù)調用的參數(shù)的數(shù)目應與函數(shù)定義完全匹配。

調用函數(shù)printme(),一定要傳遞一個參數(shù),否則會如下給出一個語法錯誤:    
#!/usr/bin/python
 
# Function definition is here
def printme( str ):
  "This prints a passed string into this function"
  print str;
  return;
 
# Now you can call printme function
printme();

當執(zhí)行上面的代碼,產生以下結果:    
Traceback (most recent call last):
 File "test.py", line 11, in <module>
  printme();
TypeError: printme() takes exactly 1 argument (0 given)

關鍵字參數(shù):

關鍵字參數(shù)是關系到函數(shù)調用。當在一個函數(shù)調用中使用關鍵字參數(shù),調用者通過參數(shù)名稱標識的參數(shù)。

這可以跳過參數(shù)或脫離順序,因為Python解釋器能夠使用提供的參數(shù)使用匹配的值的關鍵字。還可以使關鍵字調用在以下方面printme()函數(shù):    
#!/usr/bin/python
 
# Function definition is here
def printme( str ):
  "This prints a passed string into this function"
  print str;
  return;
 
# Now you can call printme function
printme( str = "My string");

當執(zhí)行上面的代碼中,產生以下結果:    
My string

下面的例子給出了更清晰的畫面。請注意,這里跟參數(shù)秩序沒有關系。    
#!/usr/bin/python
 
# Function definition is here
def printinfo( name, age ):
  "This prints a passed info into this function"
  print "Name: ", name;
  print "Age ", age;
  return;
 
# Now you can call printinfo function
printinfo( age=50, name="miki" );

當執(zhí)行上面的代碼,產生以下結果:    
Name: miki
Age 50

默認參數(shù):

默認參數(shù)是,假設一個默認值,如果不提供的函數(shù)調用的參數(shù)值的參數(shù)。下面的例子給出了默認參數(shù)一個主意,它會默認打印age,如果不通過傳值:
    
#!/usr/bin/python
 
# Function definition is here
def printinfo( name, age = 35 ):
  "This prints a passed info into this function"
  print "Name: ", name;
  print "Age ", age;
  return;
 
# Now you can call printinfo function
printinfo( age=50, name="miki" );
printinfo( name="miki" );

當執(zhí)行上面的代碼,產生以下結果:    
Name: miki
Age 50
Name: miki
Age 35

可變長度參數(shù):

可能需要處理函數(shù)比在定義函數(shù)指定多個參數(shù)。這些參數(shù)被稱為可變長度參數(shù),在函數(shù)定義沒有被命名,不像必需默認參數(shù)。

非關鍵字可變參數(shù)的函數(shù)的一般語法是這樣的:
    
def functionname([formal_args,] *var_args_tuple ):
  "function_docstring"
  function_suite
  return [expression]

星號(*)被放置,將持有的所有非關鍵字變量參數(shù)的值在變量名前。該元組保持為空,如果函數(shù)調用期間沒有指定任何其他參數(shù)。下面是一個簡單的例子:
    
#!/usr/bin/python
 
# Function definition is here
def printinfo( arg1, *vartuple ):
  "This prints a variable passed arguments"
  print "Output is: "
  print arg1
  for var in vartuple:
   print var
  return;
 
# Now you can call printinfo function
printinfo( 10 );
printinfo( 70, 60, 50 );

當執(zhí)行上面的代碼,產生以下結果:
    
Output is:
10
Output is:
70
60
50

匿名函數(shù):

可以使用lambda關鍵字來創(chuàng)建小的匿名函數(shù)。這些函數(shù)被稱為匿名,因為它們不是以標準方式通過使用def關鍵字聲明。

        Lambda形式可以采取任何數(shù)量的參數(shù),但在表現(xiàn)形式上只返回一個值。它們不能包含命令或多個表達式。
        匿名函數(shù)不能直接調用打印,因為需要lambda表達式。
        lambda函數(shù)都有自己的命名空間,并且不能訪問變量高于在其參數(shù)列表和那些在全局命名空間等。
        盡管似乎lambda是一個函數(shù)的單行版本,它們不是在C或C++,其宗旨是通過調用出于性能原因在傳遞函數(shù)的堆棧分配相當于一行的聲明。

語法

lambda函數(shù)的語法僅包含單個語句,如下:
?
1
    
lambda [arg1 [,arg2,.....argn]]:expression

以下為例子來說明函數(shù)lambda形式是如何工作的:    
#!/usr/bin/python
 
# Function definition is here
sum = lambda arg1, arg2: arg1 + arg2;
 
 
 
# Now you can call sum as a function
print "Value of total : ", sum( 10, 20 )
print "Value of total : ", sum( 20, 20 )

當執(zhí)行上面的代碼,產生以下結果:    
Value of total : 30
Value of total : 40

return語句:

該語句返回[表達式]退出功能,可選地傳遞回一個表達式給調用者。不帶參數(shù)return語句返回None。

以上所有的例子都沒有返回任何值,但如果喜歡,可以從一個函數(shù)返回值:    
#!/usr/bin/python
 
# Function definition is here
def sum( arg1, arg2 ):
  # Add both the parameters and return them."
  total = arg1 + arg2
  print "Inside the function : ", total
  return total;
 
# Now you can call sum function
total = sum( 10, 20 );
print "Outside the function : ", total

當執(zhí)行上面的代碼,產生以下結果:    
Inside the function : 30
Outside the function : 30

變量的作用域:

程序中的所有變量可能不會在該程序中的所有位置進行訪問。這取決于所聲明的變量。

變量的作用域確定了程序,可以訪問一個特定的標識符的一部分。在Python中的變量兩個基本范疇:

        全局變量
        局部變量

全局與局部變量:

這是一個函數(shù)體內部定義的變量具有局部范圍,而那些之外定義具有全局范圍。

局部變量只能在函數(shù)內部被聲明和訪問,而全局變量可以在整個程序主體由所有函數(shù)進行訪問。當調用一個函數(shù),它里面聲明的變量都納入范圍。下面是一個簡單的例子:    
#!/usr/bin/python
 
total = 0; # This is global variable.
# Function definition is here
def sum( arg1, arg2 ):
  # Add both the parameters and return them."
  total = arg1 + arg2; # Here total is local variable.
  print "Inside the function local total : ", total
  return total;
 
# Now you can call sum function
sum( 10, 20 );
print "Outside the function global total : ", total

當執(zhí)行上面的代碼,產生以下結果:    
Inside the function local total : 30
Outside the function global total : 0

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

若不方便掃碼,搜微信號:CDAshujufenxi

數(shù)據(jù)分析師考試動態(tài)
數(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(), // 加隨機數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調用 initGeetest 進行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調,回調的第一個參數(shù)驗證碼對象,之后可以使用它調用相應的接口 initGeetest({ // 以下 4 個配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗服務器是否宕機 new_captcha: data.new_captcha, // 用于宕機時表示是新驗證碼的宕機 product: "float", // 產品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說明請參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計時完成 $(".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 = '請輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請輸入正確的'+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); }