1.函數基本語法及特性
函數是什麼?
函數一詞來源於數學,但編程中的「函數」概念,與數學中的函數是有很大不同的,具體區別,我們後面會講,編程中的函數在英文中也有很多不同的叫法。在BASIC中叫做subroutine(子過程或子程序),在Pascal中叫做procedure(過程)和function,在C中只有function,在Java裏面叫做method。
定義: 函數是指將一組語句的集合通過一個名字(函數名)封裝起來,要想執行這個函數,只需調用其函數名即可
特性:
減少重複代碼
使程序變的可擴展
使程序變得易維護
語法定義
def sayhi():#函數名 print("Hello, I'm nobody!") sayhi() #調用函數
可以帶參數
#下面這段代碼 a,b = 5,8 c = a**b print(c) #改成用函數寫 def calc(x,y): res = x**y return res #返回函數執行結果 c = calc(a,b) #結果賦值給c變量 print(c)
2.函數參數與局部變量
形參變量只有在被調用時才分配內存單元,在調用結束時,即刻釋放所分配的內存單元。因此,形參只在函數內部有效。函數調用結束返回主調用函數後則不能再使用該形參變量
實參可以是常量、變量、表達式、函數等,無論實參是何種類型的量,在進行函數調用時,它們都必須有確定的值,以便把這些值傳送給形參。因此應預先用賦值,輸入等辦法使參數獲得確定值
3.默認參數
看下面代碼
def func_test(x,y):#x,y爲形參 res = x+y return res z = func_test(2,4) #2,4爲x,y的實參print(z)
test(x,y,z=9(1,2,3) test(1,z=8,y=2)test(1,2) C:\Users\congcong.du\AppData\Local\Programs\Python\Python35\python.exe C:/Users/congcong.du/PycharmProjects/test/day3/1 2 3 ------------ 1 2 8 ------------ 1 2 9 ------------
另外,你可能注意到了,在把country變成默認參數後,我同時把它的位置移到了最後面,爲什麼呢?
位置參數必須在關鍵參數前面
4.參數組*args,傳字典 **kwargs
#參數組 #若你的函數在定義時不確定用戶想傳入多少個參數,就可以使用非固定參數。 #*args 接收位置參數,不接受關鍵字參數,轉化爲元組 def test1(name,*args): print(name) print(args) test1("alex",1,2,3,4,5,5) C:\Users\congcong.du\AppData\Local\Programs\Python\Python35\python.exe C:/Users/congcong.du/PycharmProjects/test/day3/func.py alex (1, 2, 3, 4, 5, 5) print("=========字典=======")#傳字典 **kwargs :將關鍵字參數,轉換爲字典的方式 def test2(**kwargs): print(kwargs) print(kwargs["name"]) test2(name="alex",age=8,sex="man") test2(**{'age': 8, 'name': 'alex', 'sex': 'man'})#混和 def test3(name,age=18,**kwargs): print(name) print(age) print(kwargs) test3("alex", sex="man") test3("alex",1,sex="man",hobby="tsl") test3("alex",sex="man",hobby="tsl",age=1) print("---------------------") def test4(name,age=18,*args,**kwargs): print(name) print(age) print(args) print(kwargs) test4("alex",34,1,2,3,sex="man", hobby="tsl") #關鍵字參數,一定要在最後一個位置參數後maintest4("alex",age=34,sex="man",hobby="tsl")
5.局部變量
局部變量只在他的作用域內其起作用,也可以聲明爲全局變量,不過因爲寫代碼長的時候隨便聲明可能會亂,所以不推薦。
def change_name(name): print("before change:",name) name = "裏面的局部變量" print("after change:", name) name=('外面的全局變量') change_name(name) print("在外面看看name改了麼?",name) ''' before change: 外面的變量 after change 裏面的變量 在外面看看name改了麼? 外面的變量 '''
print("===========全局/局部變量=======") sex = "m" def test5(n): #global age #如果要在函數內改全局變量,用global聲明 sex = "g" #局部變量改不了全局的變量 print("before change:", n,sex) n = "Alex Li" #這個函數就是這個變量的作用域 age = 20 print("after change:", n,age,sex) name = "alex" test5(name) #print(name,age,sex) #age局部變量不能在函數外使用 print(name,sex)
函數內是可以修改全局列表的
print("======函數修改列表====") names = ["alex","jack","rain"] def change_list(): names[0]= "ALEX" print(names) change_list() print(names)
6.遞歸函數
#函數內部調用自己。 #1.必須有一個明確的結束條件,最大遞歸次數999. #2.每次進入更深一層遞歸時,問題規模相比上次遞歸應有減少 #3.效率不高,遞歸層次過多會導致棧溢出(在計算機中,函數調用是通過棧(stack)這種數據結構實現的,每當進入一個函數調用,棧就會加一層棧幀,每當函數返回,棧就會減一層棧幀。由於棧的大小不是無限的,所以,遞歸調用的次數過多,會導致棧溢出)
print("========遞歸函數=========")#函數內部調用自己。1.必須有一個明確的結束條件,最大遞歸次數999.#2.每次進入更深一層遞歸時,問題規模相比上次遞歸應有減少#3.效率不高def test6(n): print(n) if int(n/2) > 0: return test6(int(n/2)) print("-->",n) test6(10)
7.高階函數
print("========高階函數=========")#變量可以指向函數,函數的參數能接收變量,那麼一個函數就可以接收另一個函數作爲參數,這種函數就稱之爲高階函數。 #abs 轉化爲正數的函數 def add(x,y,f): return f(x)+f(y) res = add(3,-6,abs) print(res)
8.字符編碼與轉碼
Python3中默認的字符編碼爲Unicode,可以直接encode爲其他編碼
python2中默認爲windows下的gbk,所有得非Unicode都要先decode爲Unicode,然後再encode爲其他的字符編碼。
借圖
import sys print(sys.getdefaultencoding()) #顯示字符編碼 a_unicode="夫風起於青萍之末" #這個是unicode格式 print(a_unicode) a_gbk=a_unicode.encode('gbk') #默認是unicode格式,轉化爲gbk格式 print(a_gbk) a_gb2312=a_gbk.decode('gbk').encode('gb2312') #先decode轉化爲unicode格式,括號裏告訴自己是gbk格式的,再encode轉化,括號裏寫要轉化的格式。 print(a_gb2312) #gbk是gb2312升級版,常用漢字的編碼基本相同 a_unicode2=a_gbk.decode('gbk') #轉化爲unicode格式 print(a_unicode2)
9.day3 文件操作 seek tell 修改
打開文件的模式:
r, 只讀模式【默認】
w,只寫模式【不可讀;不存在則創建;存在則刪除內容;】
a, 追加模式【不可讀;不存在則創建;存在則只追加內容;】
"+" 同時讀寫某個文件:
r+,可讀寫文件。【可讀;可追加】
w+,寫讀
a+,追加讀
"U"表示在讀取時,可以將 \r \n \r\n自動轉換成 \n (與 r 或 r+ 模式同使用)
rU
r+U
"b"表示處理二進制文件(如:FTP發送上傳ISO鏡像文件,linux可忽略,windows處理二進制文件時需標註)
rb
wb
ab
1.read()、readline()、readlines()的區別
#!/usr/bin/env python #-*- coding:utf-8 -*- # Author:DCC# ##默認讀取模式 file = open("test_file","r",encoding="utf-8") #文件句柄print(file.read()) data = file.read() #所有內容 data1 = file.read() #第二次讀,是讀不出數據的 file.seek(0) #將光標歸零 data2 = file.read() #光標歸零後就可以再出讀出數據 file.close()
#!/usr/bin/env python #-*- coding:utf-8 -*- # Author:DCC file = open("test_file","r",encoding="utf-8") #文件句柄 print(file.read()) #讀出全部 file.seek(0) print(file.readline()) #讀出一行 file.seek(0) print(file.readlines()) #把文章內容以換行符分割,並生成list格式 C:\Users\congcong.du\AppData\Local\Programs\Python\Python35\python.exe C:/Users/congcong.du/PycharmProjects/test/day3/file.py 1如果你真的愛我 讓我走開 2心疼你當初反覆那樣的說 3如果你真的愛我 讓我走開 4我決心不從舊夢中 掙脫 5如果你真的愛我 讓我走開 6心疼你爲我藏住分離的苦 7如果我知道你是這樣的難過 8會一個人走向寂寞 1如果你真的愛我 讓我走開 ['1如果你真的愛我 讓我走開\n', '2心疼你當初反覆那樣的說\n', '3如果你真的愛我 讓我走開\n', '4我決心不從舊夢中 掙脫\n', '5如果你真的愛我 讓我走開\n', '6心疼你爲我藏住分離的苦\n', '7如果我知道你是這樣的難過\n', '8會一個人走向寂寞']
file = open("test_file","r",encoding="utf-8") #文件句柄 for i in range(5): print(file.readline()) #讀出前五行 file.close()
for line in file.readlines(): #轉化爲列表格式了 print(line.strip())
#!/usr/bin/env python #-*- coding:utf-8 -*- # Author:DCC file = open("test_file","r",encoding="utf-8") #文件句柄#將文件全部讀入內存 for index,line in enumerate(file.readlines()): #讀列表和下標 if index == 9: print("-----------------") continue print(line.strip()) ''' #這個效率最高,for line in file,逐行讀到內存 ''' count = 0 for line in file: if count == 9: print("--------------------") count += 1 continue print(line) count += 1 '''
#!/usr/bin/env python #-*- coding:utf-8 -*- # Author:DCC ##默認讀取模式 file = open("test_file","r",encoding="utf-8") #文件句柄 print(file.tell()) #打印光標當前的位置 print(file.readline()) print(file.readline()) print(file.readline()) print(file.tell()) file.seek(0) #移動歸零 print(file.tell()) file.flush #刷新,從內存寫到磁盤 file.close() C:\Users\congcong.du\AppData\Local\Programs\Python\Python35\python.exe C:/Users/congcong.du/PycharmProjects/test/day3/file.py 0 1如果你真的愛我 讓我走開 2心疼你當初反覆那樣的說 3如果你真的愛我 讓我走開 110 0
#!/usr/bin/env python #-*- coding:utf-8 -*- # Author:DCC #修改思路:打開一個文件,從舊文件,讀一行寫一行,改一行,寫一行 f = open("test_file","r",encoding="utf-8") f_new = open("test_file.bak","w",encoding="utf-8") for line in f: if "心疼" in line: line = line.replace("心疼","xinteng") print(line) f_new.write(line) f.close() f_new.close()
#with #python 一行不要超過80個字符,用換行\ with open("yesterday","r",encoding="utf-8") as f,\ open("yesterday2","r",encoding="utf-8") as f2: for line in f: print(line) for line2 in f2: print(line2)
10.json模塊
json模塊的作用之一:根據字符串書寫格式,將字符串自動轉換成相應格式
import json inp_str = "[11,22,33,44]" inp_list = json.loads(inp_str) # 根據字符串書寫格式,將字符串自動轉換成 列表類型 inp_str = ' {"k1":123, "k2": "wupeiqi"} ' # 正確的輸入 切記,內部必須是 雙引號 !!! #inp_str = " {'k1':123, 'k2': 'wupeiqi'}" # 錯誤的輸入 inp_dict = json.loads(inp_str) # 根據字符串書寫格式,將字符串自動轉換成 字典類型
11.startswith()函數
此函數判斷一個文本是否以某個或幾個字符開始,結果以True或者False返回。
代碼如下: text='welcome to qttc blog' print text.startswith('w') # True print text.startswith('wel') # True print text.startswith('c') # False print text.startswith('') # True
12.endswith()函數
此函數判斷一個文本是否以某個或幾個字符結束,結果以True或者False返回。
代碼如下: text='welcome to qttc blog' print text.endswith('g') # True print text.endswith('go') # False print text.endswith('og') # True print text.endswith('') # True print text.endswith('g ') # False
判斷文件是否爲exe執行文件
我們可以利用endswith()函數判斷文件名的是不是以.exe後綴結尾判斷是否爲可執行文件
代碼如下: # coding=utf8 fileName1='qttc.exe' if(fileName1.endswith('.exe')): print '這是一個exe執行文件' else: print '這不是一個exe執行文件' # 執行結果:這是一個exe執行文件
判斷文件名後綴是否爲圖片
代碼如下: # coding=utf8 fileName1='pic.jpg' if fileName1.endswith('.gif') or fileName1.endswith('.jpg') or fileName1.endswith('.png'): print '這是一張圖片' else: print '這不是一張圖片' # 執行結果:這是一張圖片