一:Python 自定義函數
函數示意圖如下:
1、使用函數的好處
- 代碼重用
- 保持一致性,易維護
- 可擴展性
2、函數定義
- 函數定義的簡單規則
- 函數代碼塊以def關鍵詞開頭
- 后接函數標識符名稱和圓括號(),名稱不能用純數字或值python保留字符定義
- 任何傳入參數和自變量必須放在圓括號中間函數內容以冒號起始,並且縮進若有返回值
- 函數通常使用三個單引號 '''...''' 來注釋說明函數;函數體內容不可為空,可用 pass 來表示空語句
- 語法如下
- 函數名稱定義的要求
- 不要以純數字命名
- 不要以python中保留字符(關鍵字)來命名
- 不要以文件名命名
- 不能出現特殊字符
- 要簡短且見名知義
def 函數名(): 函數體
3、return 返回語句
- 每個函數都有一個 return 返回值,如果沒定義則返回 None
- 函數中只要執行到 return 語句,函數就自動結束
- 可以寫多個 return 語句但是第二個及之后的 return 語句不會被執行
- 可以通過 return x,y,z 形式返回多個值
def num(a,b): c = int(a) + int(b) return a,b,c
4、參數:
- 形參:寫在函數聲明的位置的變量量叫形參
- 實參:在函數調⽤的時候給函數傳遞的值. 叫實參
- 實參可以是常量、變量、表達式、函數等,無論實參是何種類型的量,在進行函數調用時,它們都必須有確定的值,以便把這些值傳送給形參。因此應預先用賦值,輸入等辦法使參數獲得確定值.
- 傳參:給函數傳遞信息的時候將實際參數交給形式參數的過程被稱為傳參
5、參數的分類
- 位置參數
def print_info(name,school): # 定義形參 print("My name is %s" % name) print("I learning software testing in %s" % school) print_info("XiaoWang","ShenZhen Dcs") # 傳入實參 # 結果如下 My name is XiaoWang I learning software testing in ShenZhen Dcs
def add(a,b): #括號內為形參 return a+b print (add(2,3)) #括號內為實參 def jian(a,b): return a-b def cheng(a,b): return a*b def chu(a,b): return a/b #求出給定區間的偶數和 def sums(x,y): a = [] for i in range(x,y+1): if i % 2 == 0: a.append(i) return(sum(a))
-
- 示例如下
#統計出字符串中某個字母有多少個 def counts(s,x): print (s.count(x)) #分數評級方法,90分以上:A,70分以上:B,60分以上:C,其他:D
def PG(score): if score > 90: return("A") elif score > 70: return("B") elif score > 60: return("C") else: return("D")
#封裝一個功能,實現統計文件內容行數 def count_line(filepath): with open(filepath,"r") as data: return(len(data.readlines()))
#coding=utf-8 """ 封裝登錄和注冊方法進行登錄注冊要求如下: 先定義一個字典來存放用戶名,賬號和密碼如dic = {'admin': '123456', 'xfs': '234567'} 要求如下: 1、從字典中獲取用戶完成登入,登入時判斷用戶是否存在,存在直接登入 2、如果輸入的登入用戶判斷不存在字典,則調用注冊方法,完成該用戶的注冊,注冊成功后寫入字典 """ dic = {'admin':'123456','xfs':'234567'} def register(): user = input("輸入賬號:") A = True while A: pwd = input("輸入密碼:") repwd = input("請確認密碼:") if repwd == pwd: dic.setdefault(user,pwd) A = False else: print ("兩次密碼不一致!") def login(): user = input("請輸入賬號:") if user in dic.keys(): for i in range(3): pwd = input("請輸入密碼:") if pwd == dic.get(user): print ("登錄成功") break else: print ("密碼錯誤") else: print ("賬號不存在,請注冊!") register() login()
#coding=utf-8 #封裝一個方法,實現人民幣和美元匯率轉換 def Change(a): if a[:3] == "¥": return("%.4f" % (float(a[3:])/6.78)) elif a[:1] == "$": return ("%.4f" % (float(a[1:])*6.78)) else: return "輸入有誤!"
- 默認參數
- 默認形參必須接在位置參數后
def print_info(name = "XiaoZhen",school = "ShangHai Dcs"): print("My name is %s" % name) print("I learning software testing in %s" % school) print_info() # 未傳實參 print_info("XiaoWang","ShenZhen Dcs") # 重新傳了實參 # 結果如下 My name is XiaoZhen I learning software testing in ShangHai Dcs My name is XiaoWang I learning software testing in ShenZhen Dcs
def print_info(name,school = "GuangZhou Dcs"): print("My name is %s" % name) print("I learning software testing in %s" % school) print_info("XiaoWang","ShenZhen Dcs") #結果如下 My name is XiaoWang I learning software testing in ShenZhen Dcs
# 默認參數在位置參數前
def print_info(name = "XiaoZheng",school): # 此時默認參數在位置參數前,代碼會提示報錯
print("My name is %s" % name)
print("I learning software testing in %s" % school)
- 可變長參數
- 建議可變長參數放在默認參數后
def abc(x,*y): return x,y abc(1,2) abc(1,2,3,4,5,6)
def abc(*args): for i in args: print(i) print(args) #args 中存儲了(1, 2, 3, 4, 5) print(*args) #輸出的時候加上 * 可以去除() abc(1,2,3,4,5) #結果如下 1 2 3 4 5 (1, 2, 3, 4, 5) 1 2 3 4 5
# 將可變長參數放在默認參數前 def print_info(name,*args,age = 24,**kwargs): print("My name is %s" % name) print("My teachers are %s" % (str(args))) print("My age is %s" % age) print("I learning software testing in %s" % (kwargs.get("School"))) print_info("XiaoZheng","Qian Sir","Chen Sir","Zheng Sir",27,School="ShenZhen Dcs") # 結果如下 My name is XiaoZheng My teachers are ('Qian Sir', 'Chen Sir', 'Zheng Sir', 27) # 解釋器將我傳給 age 的實參 27 也當作 args 的參數了 My age is 24 # 我在調用函數時傳給 age 的實參未生效 I learning software testing in ShenZhen Dcs
- 關鍵字參數
- 關鍵字參數必須放在可變長參數后
def print_info(name,school): print("My name is %s" % name) print("I learning software testing in %s" % school) print_info(school="ShangHai Dcs",name="XiaoZheng") # 第一種傳參方式 print_info(**{"name":"XiaoWang","school":"ShenZhen Dcs"}) # 第二種傳參方式 info = {"name":"XiaoQian","school":"GuangZhou Dcs"} print_info(**info) # 第三種傳參方式 # 結果如下 My name is XiaoZheng I learning software testing in ShangHai Dcs My name is XiaoWang I learning software testing in ShenZhen Dcs My name is XiaoQian I learning software testing in GuangZhou Dcs
def abc(x,**kwargs): return x,kwargs #傳參方式如下 stu = {"name":"zhangsan","age":20} print (abc(1,**stu)) print (abc(1,name="zhangsan",age=20)) print (abc(1,**{"name":"zhangsan","age":20}))
# 關鍵字參數放在可變長參數后 def print_info(name,age = 24,*args,**kwargs): print("My name is %s" % name) # 位置參數 print("My age is %s" % age) # 默認參數 print("My teachers are %s" % (str(args))) # 可變長參數 print("I learning software testing in %s" % (kwargs.get("School"))) # 關鍵字參數 print_info("XiaoZheng",27,"Qian Sir","Chen Sir","Zheng Sir",School="ShenZhen Dcs") # 結果如下 My name is XiaoZheng My age is 27 My teachers are ('Qian Sir', 'Chen Sir', 'Zheng Sir') I learning software testing in ShenZhen Dcs # 關鍵字參數放在可變長參數前 def print_info(name,age = 24,**kwargs,*args): # 代碼會提示報錯 print("My name is %s" % name) print("My age is %s" % age) print("My teachers are %s" % (str(args))) print("I learning software testing in %s" % (kwargs.get("School")))
6、作用域(局部變量和全局變量)
- 局部變量是在函數內部定義的變量,只能在函數內部使用,函數執行結束后,函數內部的局部變量,會被系統回收不同的函數,不同函數可以定義相同的名字的局部變量,但是各用各的不會產生影響
- 全局變量是在函數外部定義的變量,(沒有定義在某一個函數內),所有函數內部都可以使用這個變量