標籤:home style python rgs enter 結果 作用 txt pen
一、函數是什麼:
函數是指將一組語句的集合通過一個名字(函數名)封裝起來,要想執行這個函數,只需要調用函數名就行。
二、函數的作用:
1、簡化代碼
2、提高代碼的複用性
3、代碼可擴充
三、定義函數:
1 def SayHello(): #函數名2 print(‘Hello‘)#函數體3 SayHello() #調用函數,函數不調用是不會被執行的
四、函數的參數
位置參數:必填參數
1 def calc(a,b): #形參,形式參數2 res = a * b3 print(‘%s * %s = %s‘%(a,b,res))4 calc(8.9,2.7) #實參,實際參數
預設值參數:非必填參數
1 # 操作檔案函數(讀和寫) 2 def op_file(file_name,conent=None): #conent為寫的內容 3 f = open(file_name,‘a+‘,encoding=‘utf-8‘) 4 f.seek(0) 5 if conent: #conent不為空白代表寫入檔案 6 f.write(conent) 7 f.flush() 8 else: #conent為空白時讀檔案 9 all_users = f.read() #函數裡面定義的局部變數只能在函數裡面用10 return all_users #調用完函數之後,返回什麼結果11 f.close()12 # 把函數返回的結果存入變數13 res = op_file(‘a.txt‘)14 print(res)
非固定參數(參數組):
1、非必填參數
2、不限定參數個數
3、把所有參數放到一個元組裡面
1 def syz(*args): #參數組 2 print(args) 3 username = args[0] 4 pwd = args[1] 5 age = args[2] 6 syz() 7 syz(‘niuniu‘,‘123‘) 8 syz(‘niuniu‘,‘niuniu‘,‘test‘) 9 def syz2(a,*args):10 print(a)11 username = args[0]12 pwd = args[1]13 age = args[2]14 syz2()15 syz2(‘niuniu‘,‘123‘)16 syz2(‘niuniu‘,‘niuniu‘,‘test‘)
關鍵字參數:
1、非必填參數
2、不限定參數個數
3、把所有參數放到一個字典裡面
1 def syz(**kwargs): 2 print(kwargs) 3 syz() 4 syz(name=‘niuniu‘,age=23) 5 syz(name=‘niuniu‘,age=23,add=‘回龍觀‘,home=‘河南‘) 6 def syz2(time,**kwargs): 7 print(kwargs) 8 syz2(‘20180418‘) 9 syz2(name = ‘niuniu‘,age = 23,time = ‘20180418‘)10 syz2(‘20180418‘,name = ‘niuniu‘,age = 23,add = ‘回龍觀‘,home = ‘河南‘)
五、全域變數
1、不安全,所有人都能改
2、全域變數會一直佔用記憶體
1 name = ‘牛牛‘ #全域變數2 def sayName():3 global name #如果需要修改全域變數,需要先聲明4 name = ‘劉偉‘#局部變數5 print(‘name1:‘,name)6 sayName()7 print(‘name2:‘,name)
六、遞迴函式:函數自己調用自己
1、少用遞迴
2、遞迴最多調用999次,效率不高
1 def test():2 num = int(input(‘please enter a number:‘))3 if num % 2 == 0:#判斷輸入的數字是不是偶數4 return True #如果是偶數的話,程式就退出了,返回True5 print(‘不是偶數請重新輸入!‘)6 return test() #如果不是偶數的話繼續調用自己,輸入值7 print(test()) #調用函數
七、函數返回多個值
1 # 定義一個函數返回多個值 2 def say(): 3 num1 = 1 4 num2 = 2 5 num3 = 3 6 return num1,num2,num3 7 # 函數返回多個值會把它放到一個元組裡面 8 print(say()) 9 # 函數如果返回多個值,可以用多個變數來接收10 res1,res2,res3 = say()11 print(res1)12 print(res2)13 print(res3)
Python學習之==>函數