1. 程式人生 > 實用技巧 >python學習第7天----函式定義、引數、返回值

python學習第7天----函式定義、引數、返回值

1.函式

對程式碼塊和功能的封裝和定義,即對某個功能直接進行封裝,當需要該功能時,直接呼叫函式

1)函式的定義

def 函式名():

函式體

2)函式呼叫:

函式名()

例:函式的定義和呼叫

def play():         #函式定義
    print("吃飯")
    print("睡覺")
    print("打豆豆")
play()          #函式呼叫
print("哈哈哈哈")
play()
View Code

3)函式的返回

執行完函式之後,可以使用return來返回結果

def play():         #函式定義
    print("
吃飯") print("睡覺") print("打豆豆") return "吃喝玩樂" #當函式結束的時候,給呼叫方一個結果 res = play() #函式呼叫,並接受返回結果 print(res) 輸出: 吃飯 睡覺 打豆豆 吃喝玩樂
View Code

①每個函式如果在函式中不寫return,預設返回None

②如果在return後面啥也不寫,預設也是返回None

③只要函式執行到return,函式就會停止執行

④可以只寫一個return,也是返回None,表示停止函式的執行

⑤return 一個返回值 ; 可在呼叫方接受到一個返回值

⑥return 多個返回值 ; 多個返回值需要用逗號隔開,多個返回值在接受的位置,接受到的時元組型別的資料

def play():         #函式定義
    print("吃飯")
    print("睡覺")
    print("打豆豆")
res = play()   #函式呼叫,並接受返回結果
print(res)
輸出:
吃飯
睡覺
打豆豆
None
View Code

#函式存在多個返回值

def play():         #函式定義
    print("打豆豆")
    return "吃飯","睡覺","玩遊戲"
a,b,c = play()
print(a)
print(b)
print(c)
輸出:
打豆豆
吃飯
睡覺
玩遊戲
View Code

4)函式的引數

引數:在函式執行的時候,給函式傳遞的資訊

形參:在函式宣告的位置,宣告出來的遍歷

實參:在函式呼叫的時候實際給函式傳遞的值

def play(func):         #func為形參
    print("吃飯")
    print("打%s" % func)
play("遊戲")
play("豆豆")           #實參
View Code

#可以給函式傳遞多個引數,每個引數之間用逗號隔開

def play(func,game):         #函式定義
    print("吃飯")
    print("玩%s" % func)
    print("遊戲名稱為 %s" % game)
play("遊戲","LOL")
輸出:
吃飯
玩遊戲
遊戲名稱為 LOL
View Code

注:函式的參時個數是沒有要求的,但是程式在執行的時候,要按照位置把實參賦值給形參

#實參的角度,對於引數的分類:

①位置引數

②關鍵字引數

③混合引數:混合引數應注意書寫順序,先寫位置引數,然後在寫關鍵字引數,否則會報錯

def people(id,name,age,add,email):
    print("ID:%s,姓名:%s,年齡:%s,地址:%s,郵箱:%s" % (id,name,age,add,email))
people("101","zz","23","蘭州","[email protected]")  #位置引數
people(name="ha",age="20",add="西安",id="102",email="[email protected]")  #關鍵字引數
people("103",name="er",age="4",add="lanzhou",email="[email protected]")  #混合引數
輸出:
ID:101,姓名:zz,年齡:23,地址:蘭州,郵箱:88888@qq.com
ID:102,姓名:ha,年齡:20,地址:西安,郵箱:00000@163.com
ID:103,姓名:er,年齡:4,地址:lanzhou,郵箱:[email protected]
View Code

#形參的角度,對於引數的分類

①位置引數

②預設值引數:在定義時,給形參一個預設值,實參傳值時,若不寫,使用預設值

③位置引數和預設值引數混和用。順序:先寫位置引數,然後再寫預設值引數

#預設值引數使用

def people(name,age,sex=""):
    print("姓名:%s,年齡:%s,性別: %s" % (name,age,sex))
people("張三",18)
people("李四",20)
people("小紅",23,"")
輸出:
姓名:張三,年齡:18,性別: 男
姓名:李四,年齡:20,性別: 男
姓名:小紅,年齡:23,性別: 女
View Code

例1:1+。。。。+n

def sum(n):
    s = 0
    count =1
    while count <= n:
        s = s + count
        count = count +1
    return s
res = sum(100)
print(res)
輸出:
5050
View Code

例2:計算n是奇數還是偶數

def fn(n):
    if n%2 ==0:
        return "偶數"
    else:
        return "奇數"
print(fn(321))
輸出:
奇數
View Code

2.練習

1)寫一個函式,檢查獲取傳入列表或元組物件(即傳入的引數為列表或者元組)的所有奇數位索引對於的元素,並將其作為新列表返回給呼叫者

def func(lst):
    lst_new =[]
    for i in range(len(lst)):
        if i % 2 == 1:
            lst_new.append(lst[i])
    return lst_new
a = [1,10,13,2,8,17]
s = func(a)
print(s)
輸出:
[10, 2, 17]
View Code

2)寫一個函式,判斷使用者傳入的物件(字串,列表,元組)長度是否大於5

注:對於判斷類的函式,返回值建議寫True或者False

def func(a):
    if len(a) >5:
        return True
    else:
        return False
res = func("我愛北京天安門")
print(res)
輸出:
True
View Code

3)寫一個函式,檢查傳入列表的長度,如果列表長度大於2,將列表的前2項返回給呼叫者

def func(lst):
    if len(lst) > 5:
        return  lst[0],lst[1]
a,b = func(lst=[10,20,5,8,7,9,6])
print(a,b)
輸出:
10 20 
View Code

4)寫一個函式,計算傳入函式的字串中的數字,字母,空格,以及其他內容 的個數,並返回結果

def func(s=""):
    num = 0
    word =0
    space =0
    other = 0
    for i in s:
        if i.isdigit():
            num +=1
        elif i.isalnum():
            word += 1
        elif i == " ":
            space += 1
        else:
            other +=1
    return  num,word,space,other
str = "AAAA2222  @@  #"
print(func(str))
輸出:
(4, 4, 4, 3)
View Code

5)寫一個函式,接受兩個引數,返回比較大的那個數字

def func(a,b):
    return a if a>b else b
print(func(3,5))
輸出:
5
View Code

6)寫一個函式,檢查傳入字典的每一個value的長度,如果value的長度大於2,那麼僅保留前兩個長度的內容,並將新內容返回給呼叫著(注:字典中的value只能是字串或列表)

如dic={'k1':"vvvv",'k2':[11,22,33,44]} 改變為dic={'k1':"vv",'k2':"[11,22]"}

def func(dic):
    dic_new = {}
    for k,v in dic.items():
        if len(v) > 2:
            dic_new[k] = v[0:2]
        else:
            dic_new[k] = v
    return dic_new
dic={'k1':"vvvv",'k2':[11,22,33,44]}
print(func(dic))
輸出:
{'k1': 'vv', 'k2': [11, 22]}
View Code

7)寫一個函式,此函式只接受一個引數且引數必須是列表資料型別,此函式完成的功能是返回呼叫者一個字典,此字典的鍵值對位此列表的索引以及對於的元素。例如傳入的列表為[11,22,33]則返回的字典為{0:11,1::22,2:33}

def func(lst):
    dic = {}
    for i in range(len(lst)):
        dic[i] = lst[i]
    return dic
lst = ["哈哈","呵呵","吼吼"]
print(func(lst))
輸出:
{0: '哈哈', 1: '呵呵', 2: '吼吼'}
View Code

8)寫一個函式,函式接受四個引數分別為:姓名、性別、年齡、學歷。使用者通過輸入這四個內容,然後將這四個內容傳入到函式中,此函式接受到這四個內容,將內容追加到一個student_msg檔案中

def funn(name,sex,age,edu):
    f = open("student.msg",mode="a",encoding="utf-8")
    f.write(name+"_"+sex+"_"+"_"+age+"_"+edu)
    f.flush()
    f.close()
    return name,sex,age,edu
a = input("請輸入姓名:")
b = input("請輸入性別:")
c = input("請輸入年齡:")
d = input("請輸入學歷:")
print(funn(a,b,c,d))
輸入輸出:
請輸入姓名:zdz
請輸入性別:男
請輸入年齡:20
請輸入學歷:小學
('zdz', '', '20', '小學')
View Code

9)對上一題升級:支援使用者持續輸入,按Q或者q退出,性別預設為男,如果遇到nv學生,則把性別輸入女

def funn(name,age,edu,sex=""):
    f = open("student.msg",mode="a",encoding="utf-8")
    f.write(name+"_"+sex+"_"+"_"+age+"_"+edu+"\n")
    f.flush()
    f.close()
    return name,sex,age,edu
while 1 :
    content = input("是否錄入學生資訊,Q/q退出:")
    if content.upper() == "Q":
        break
    a = input("請輸入姓名:")
    b = input("請輸入性別:")
    c = input("請輸入年齡:")
    d = input("請輸入學歷:")
    funn(a,b,c,d)
View Code

10.寫一個函式,使用者摻入修改的檔名與要修改的內容,執行函式,完成整個檔案的批量修改操作

import  os
def func(filename,old,new):
    with open(filename,mode="r",encoding="utf-8") as f1, \
        open(filename+"_副本",mode="w",encoding="utf-8") as f2:
        for line in f1:
            s = line.replace(old,new)
            f2.write(s)
    os.remove(filename)
    os.replace(filename+"_副本",filename)
func("student.msg","小學","大學")
View Code