Python之路 函數基礎

來源:互聯網
上載者:User

標籤:文法   如何   nal   賬戶   sub   *args   dev   temp   readlines   

基本定義函數是什麼?

函數一詞來源於數學,但編程中的「函數」概念,與數學中的函數是有很大不同的,具體區別,我們後面會講,編程中的函數在英文中也有很多不同的叫法。在BASIC中叫做subroutine(子過程或子程式),在Pascal中叫做procedure(過程)和function,在C中只有function,在Java裡面叫做method。

定義: 函數是指將一組語句的集合通過一個名字(函數名)封裝起來,要想執行這個函數,只需調用其函數名即可

特性:

  1. 減少重複代碼
  2. 使程式變的可擴充
  3. 使程式變得易維護
文法定義
def sayhi():#函數名    print("Hello, I‘m nobody!")sayhi() #調用函數

可以帶參數

#下面這段代碼a,b = 5,8c = a**bprint(c)#改成用函數寫def calc(x,y):    res = x**y    return res #返回函數執行結果c = calc(a,b) #結果賦值給c變數print(c)

參數可以讓你的函數更靈活,不只能做死的動作,還可以根據調用時傳參的不同來決定函數內部的執行流程

函數參數

形參變數

只有在被調用時才分配記憶體單元,在調用結束時,即刻釋放所分配的記憶體單元。因此,形參只在函數內部有效。函數調用結束返回主調用函數後則不能再使用該形參變數

實參

可以是常量、變數、運算式、函數等,無論實參是何種類型的量,在進行函數調用時,它們都必須有確定的值,以便把這些值傳送給形參。因此應預先用賦值,輸入等辦法使參數獲得確定值

預設參數

看如下代碼

def stu_register(name,age,country,course):    print("----註冊學生資訊------")    print("姓名:",name)    print("age:",age)    print("國籍:",country)    print("課程:",course)stu_register("王山炮",22,"CN","python_devops")stu_register("張叫春",21,"CN","linux")stu_register("劉老根",25,"CN","linux")

發現 country 這個參數 基本都 是"CN", 就像我們在網站上註冊使用者,像國籍這種資訊,你不填寫,預設就會是 中國, 這就是通過預設參數實現的,把country變成預設參數非常簡單

def stu_register(name,age,course,country="CN"):

這樣,這個參數在調用時不指定,那預設就是CN,指定了的話,就用你指定的值。

另外,你可能注意到了,在把country變成預設參數後,我同時把它的位置移到了最後面,為什麼呢?  

關鍵參數

正常情況下,給函數傳參數要按順序,不想按順序就可以用關鍵參數,只需指定參數名即可(指定了參數名的參數就叫關鍵參數),但記住一個要求就是,關鍵參數必須放在位置參數(以位置順序確定對應關係的參數)之後

def stu_register(name, age, course=‘PY‘ ,country=‘CN‘):    print("----註冊學生資訊------")    print("姓名:", name)    print("age:", age)    print("國籍:", country)    print("課程:", course)

調用可以這樣

stu_register("王山炮",course=‘PY‘, age=22,country=‘JP‘ )

但絕不可以這樣

stu_register("王山炮",course=‘PY‘,22,country=‘JP‘ )

當然這樣也不行

stu_register("王山炮",22,age=25,country=‘JP‘ )

這樣相當於給age賦值2次,會報錯!

非固定參數

若你的函數在定義時不確定使用者想傳入多少個參數,就可以使用非固定參數

def stu_register(name,age,*args): # *args 會把多傳入的參數變成一個元組形式    print(name,age,args)stu_register("Alex",22)#輸出#Alex 22 () #後面這個()就是args,只是因為沒傳值,所以為空白stu_register("Jack",32,"CN","Python")#輸出# Jack 32 (‘CN‘, ‘Python‘)

還可以有一個**kwargs

def stu_register(name,age,*args,**kwargs): # *kwargs 會把多傳入的參數變成一個dict形式    print(name,age,args,kwargs)stu_register("Alex",22)#輸出#Alex 22 () {}#後面這個{}就是kwargs,只是因為沒傳值,所以為空白stu_register("Jack",32,"CN","Python",sex="Male",province="ShanDong")#輸出# Jack 32 (‘CN‘, ‘Python‘) {‘province‘: ‘ShanDong‘, ‘sex‘: ‘Male‘}
傳回值

函數外部的代碼要想擷取函數的執行結果,就可以在函數裡用return語句把結果返回

def stu_register(name, age, course=‘PY‘ ,country=‘CN‘):    print("----註冊學生資訊------")    print("姓名:", name)    print("age:", age)    print("國籍:", country)    print("課程:", course)    if age > 22:        return False    else:        return Trueregistriation_status = stu_register("王山炮",22,course="PY全棧開發",country=‘JP‘)if registriation_status:    print("註冊成功")else:    print("too old to be a student.")

注意

  • 函數在執行過程中只要遇到return語句,就會停止執行並返回結果,so 也可以理解為 return 語句代表著函數的結束
  • 如果未在函數中指定return,那這個函數的傳回值為None
全域與局部變數
name = "Alex Li"def change_name(name):    print("before change:",name)    name = "金角大王,一個有Tesla的男人"    print("after change", name)change_name(name)print("在外面看看name改了麼?",name)

輸出

before change: Alex Liafter change 金角大王,一個有Tesla的男人在外面看看name改了麼? Alex Li

不用傳name 值到函數裡,也可以在函數裡調用外面的變數

name = "Alex Li"def change_name():    name = "金角大王,一個有Tesla的男人"    print("after change", name)change_name()print("在外面看看name改了麼?", name)

但就是不能改!

  • 在函數中定義的變數稱為局部變數,在程式的一開始定義的變數稱為全域變數。
  • 全域變數範圍是整個程式,局部變數範圍是定義該變數的函數。
  • 當全域變數與局部變數同名時,在定義局部變數的函數內,局部變數起作用;在其它地方全域變數起作用。
範圍

範圍(scope),程式設計概念,通常來說,一段程式碼中所用到的名字並不總是有效/可用的,而限定這個名字的可用性的代碼範圍就是這個名字的範圍。

這裡不適合深入,以後再講LEGB rule

如何在函數裡修改全域變數?
name = "Alex Li"def change_name():    global name    name = "Alex 又名 金角大王,路飛學城講師"    print("after change", name)change_name()print("在外面看看name改了麼?", name)

global name的作用就是要在函數裡聲明全域變數name ,意味著最上面的name = "Alex Li"即使不寫,程式最後面的print也可以列印name

嵌套函數
name = "Alex"def change_name():    name = "Alex2"    def change_name2():        name = "Alex3"        print("第3層列印", name)    change_name2()  # 調用內層函數    print("第2層列印", name)change_name()print("最外層列印", name)

輸出

第3層列印 Alex3第2層列印 Alex2最外層列印 Alex

此時,在最外層調用change_name2()會出現什麼效果?

沒錯, 出錯了, 為什麼呢?

嵌套函數的用法會了,但它有什麼用呢?下節課揭曉。。。

匿名函數

匿名函數就是不需要顯式的指定函數名

#這段代碼def calc(x,y):    return x**yprint(calc(2,5))#換成匿名函數calc = lambda x,y:x**yprint(calc(2,5))

你也許會說,用上這個東西沒感覺有毛方便呀, 。。。。呵呵,如果是這麼用,確實沒毛線改進,不過匿名函數主要是和其它函數搭配使用的呢,如下

res = map(lambda x:x**2,[1,5,7,4,8])for i in res:    print(i)

輸出

125491664
高階函數

變數可以指向函數,函數的參數能接收變數,那麼一個函數就可以接收另一個函數作為參數,這種函數就稱之為高階函數。

def add(x,y,f):    return f(x) + f(y)res = add(3,-6,abs)print(res)

只需滿足以下任意一個條件,即是高階函數

  • 接受一個或多個函數作為輸入
  • return 返回另外一個函數
遞迴

在函數內部,可以調用其他函數。如果一個函數在內部調用自身本身,這個函數就是遞迴函式。

def calc(n):    print(n)    if int(n/2) ==0:        return n    return calc(int(n/2))calc(10)

輸出

10521

來看實現過程,我改了下代碼

def calc(n):    v = int(n/2)    print(v)    if v > 0:        calc(v)    print(n)calc(10)

輸出

521012510

為什麼輸出結果是這樣?

遞迴特性:

  1. 必須有一個明確的結束條件
  2. 每次進入更深一層遞迴時,問題規模相比上次遞迴都應有所減少
  3. 遞迴效率不高,遞迴層次過多會導致棧溢出(在電腦中,函數調用是通過棧(stack)這種資料結構實現的,每當進入一個函數調用,棧就會加一層棧幀,每當函數返回,棧就會減一層棧幀。由於棧的大小不是無限的,所以,遞迴調用的次數過多,會導致棧溢出)

堆棧掃盲http://www.cnblogs.com/lln7777/archive/2012/03/14/2396164.html

遞迴有什麼用呢?有很多用途,今天我們就講一個

遞迴函式實際應用案例,二分尋找

data = [1, 3, 6, 7, 9, 12, 14, 16, 17, 18, 20, 21, 22, 23, 30, 32, 33, 35]def binary_search(dataset,find_num):    print(dataset)    if len(dataset) >1:        mid = int(len(dataset)/2)        if dataset[mid] == find_num:  #find it            print("找到數字",dataset[mid])        elif dataset[mid] > find_num :# 找的數在mid左面            print("\033[31;1m找的數在mid[%s]左面\033[0m" % dataset[mid])            return binary_search(dataset[0:mid], find_num)        else:# 找的數在mid右面            print("\033[32;1m找的數在mid[%s]右面\033[0m" % dataset[mid])            return binary_search(dataset[mid+1:],find_num)    else:        if dataset[0] == find_num:  #find it            print("找到數字啦",dataset[0])        else:            print("沒的分了,要找的數字[%s]不在列表裡" % find_num)binary_search(data,66)
內建函數

Python的len為什麼你可以直接用?肯定是解譯器啟動時就定義好了

內建參數詳解 https://docs.python.org/3/library/functions.html?highlight=built#ascii

幾個刁鑽古怪的內建方法用法提醒

#compilef = open("函數遞迴.py")data =compile(f.read(),‘‘,‘exec‘)exec(data)#printmsg = "又回到最初的起點"f = open("tofile","w")print(msg,"記憶中你青澀的臉",sep="|",end="",file=f)# #slice# a = range(20)# pattern = slice(3,8,2)# for i in a[pattern]: #等於a[3:8:2]#     print(i)###memoryview#usage:#>>> memoryview(b‘abcd‘)#<memory at 0x104069648>#在進行切片並賦值資料時,不需要重新copy原列表資料,可以直接映射原資料記憶體,import timefor n in (100000, 200000, 300000, 400000):    data = b‘x‘*n    start = time.time()    b = data    while b:        b = b[1:]    print(‘bytes‘, n, time.time()-start)for n in (100000, 200000, 300000, 400000):    data = b‘x‘*n    start = time.time()    b = memoryview(data)    while b:        b = b[1:]    print(‘memoryview‘, n, time.time()-start)幾個內建方法用法提醒
練習題

修改個人資訊程式

在一個檔案裡存多個人的個人資訊,如以下

username password  age position department alex     abc123    24   Engineer   ITrain     [email protected]    25   Teacher   Teching....

1.輸入使用者名稱密碼,正確後登入系統 ,列印

1. 修改個人資訊2. 列印個人資訊3. 修改密碼

2.每個選項寫一個方法

3.登入時輸錯3次退出程式

練習題答案

def print_personal_info(account_dic,username):    """    print user info     :param account_dic: all account‘s data     :param username: username     :return: None    """    person_data = account_dic[username]    info = ‘‘‘    ------------------    Name:   %s    Age :   %s    Job :   %s    Dept:   %s    Phone:  %s    ------------------    ‘‘‘ %(person_data[1],          person_data[2],          person_data[3],          person_data[4],          person_data[5],          )    print(info)def save_back_to_file(account_dic):    """    把account dic 轉成字串格式 ,寫迴文件     :param account_dic:     :return:     """    f.seek(0) #回到檔案頭    f.truncate() #清空原檔案    for k in account_dic:        row = ",".join(account_dic[k])        f.write("%s\n"%row)    f.flush()def change_personal_info(account_dic,username):    """    change user info ,思路如下    1. 把這個人的每個資訊列印出來, 讓其選擇改哪個欄位,使用者選擇了的數字,正好是欄位的索引,這樣直接 把欄位找出來改掉就可以了    2. 改完後,還要把這個新資料重新寫回到account.txt,由於改完後的新資料 是dict類型,還需把dict轉成字串後,再寫回硬碟     :param account_dic: all account‘s data     :param username: username     :return: None    """    person_data = account_dic[username]    print("person data:",person_data)    column_names = [‘Username‘,‘Password‘,‘Name‘,‘Age‘,‘Job‘,‘Dept‘,‘Phone‘]    for index,k in enumerate(person_data):        if index >1: #0 is username and 1 is password            print("%s.  %s: %s" %( index, column_names[index],k)  )    choice = input("[select column id to change]:").strip()    if choice.isdigit():        choice = int(choice)        if choice > 0 and choice < len(person_data): #index不能超出列表長度邊界            column_data = person_data[choice] #拿到要修改的資料            print("current value>:",column_data)            new_val = input("new value>:").strip()            if new_val:#不為空白                person_data[choice] = new_val                print(person_data)                save_back_to_file(account_dic) #改完寫迴文件            else:                print("不可為空。。。")account_file = "account.txt"f = open(account_file,"r+")raw_data = f.readlines()accounts = {}#把賬戶資料從檔案裡讀書來,變成dict,這樣後面就好查詢了for line in raw_data:    line = line.strip()    if not  line.startswith("#"):        items = line.split(",")        accounts[items[0]] = itemsmenu = ‘‘‘1. 列印個人資訊2. 修改個人資訊3. 修改密碼‘‘‘count = 0while count <3:    username = input("Username:").strip()    password = input("Password:").strip()    if username in accounts:        if password == accounts[username][1]: #            print("welcome %s ".center(50,‘-‘) % username )            while True: #使使用者可以一直停留在這一層                print(menu)                user_choice = input(">>>").strip()                if user_choice.isdigit():                    user_choice = int(user_choice)                    if user_choice == 1:                        print_personal_info(accounts,username)                    elif user_choice == 2:                        change_personal_info(accounts,username)                elif user_choice == ‘q‘:                    exit("bye.")        else:            print("Wrong username or password!")    else:        print("Username does not exist.")    count += 1else:    print("Too many attempts.")

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.