十一、python函數學習

來源:互聯網
上載者:User

標籤:UNC   fun   pytho   global   bsp   修改   turn   形參   dict   

1.    定義函數

def   函數名(形參):

    函數體

    return  xxx--------其下面的內容不再執行

---------------------------------------------------------------------------------------------------------------

2.執行函數

      函數名(實參)

---------------------------------------------------------------------------------------------------------------

3.形參,實參(預設按照順序)

---------------------------------------------------------------------------------------------------------------

4.執行形參傳入實參,可不按照順序

---------------------------------------------------------------------------------------------------------------

5.函數可以有預設參數

---------------------------------------------------------------------------------------------------------------

6.動態參數  
#動態參數一,類型為元祖,傳的參數為元祖的元素
def f1(*a):
print (a,type(a))
f1(123,234,[456123789],{1:2})
#動態參數二,類型為字典,傳入的參數為字典的索引值對
def f1(**a):
print (a,type(a))
f1(k1=123,k2=456)
#萬能動態參數-------一*較**在前
def f1(*a,**p):
print (a,type(a),type(p))
f1(123,234,[456123789],{1:2},k1=123,k2=456)
---------------------

    ((123, 234, [456123789], {1: 2}), <type ‘tuple‘>)
    ({‘k2‘: 456, ‘k1‘: 123}, <type ‘dict‘>)
    ((123, 234, [456123789], {1: 2}), <type ‘tuple‘>, <type ‘dict‘>)

---------------------------------------------------------------------------------------------------------------

7.為動態參數傳入字典,列表

def f1(*args):
print (args,type(args))
l1=[11,22,33,44]
f1(l1)
f1(*l1)
------------------------

 (([11, 22, 33, 44],), <type ‘tuple‘>)
 ((11, 22, 33, 44), <type ‘tuple‘>)

------------------------

def f2(**args):
print (args,type(args))
l1={"k1":"123"}
f2(l1=l1)
f2(**l1)
-------------------------

   ({‘l1‘: {‘k1‘: ‘123‘}}, <type ‘dict‘>)
   ({‘k1‘: ‘123‘}, <type ‘dict‘>)

---------------------------------------------------------------------------------------------------------------

8.全域變數,局部變數

P="chushujin"
def func1():
#局部變數
a=123
global P #加上此關鍵詞後,全域變數就會被修改,否則不會被修改
print (a)
P="zhangyu"
def func2():
print (P)
func1()
func2()
----------------------

   123
 zhangyu

十一、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.