【筆記】Python編程 從入門到實踐 第二版(基礎部分)
- 2021 年 7 月 18 日
- 筆記
1 字元串相關函數
- .title() # 將字元串每個單詞的首字母大寫
- .upper() #不改變字元串變數的值
- .lower() #不改變字元串變數的值
- f”{var} ,字元串” # 將變數和字元串格式化
- .rstrip() # 去除字元串尾空格,暫時的,再次訪問還原
- .lstrip() # 去除字元串頭空格
- .strip() # 去除字元串 頭和尾的空格
- .split() # 以空格 將字元串拆分成列表
2 計算符號
- 3**2 # 9 3的2次方
- 1_000_0000 # 大數可以使用_分割 不會影響
3 import this #Python之禪
4 列表
特定順序排列元素組成;元素間可無關係(不必同類型);索引從0開始;-1表示最後一個元素;
- .append() # 列表末尾添加元素
- .insert(index,var) # 在index處插入一個值,後面依次右移
- del list[index] # 刪除index索引處元素,後面依次左移
- .pop() # 刪除列表尾一個元素
- .pop(index) # 刪除index處元素
- .remove(var) # 刪除列表中第一出現的var
- .sort() # 按照字母表順序,大小排序;永久性;字母數字不可混合排序;
- sorted(list) # 臨時排序,再次訪問還原
- .reverse() # 反轉列表順序
- len(list) # 確定列表長度
- 遍歷列表
# 依據冒號和縮進 for var in list: print(var)
- range 創建數值列表
# 1 2 3 4 ;range(m,n) 最後m到n-1;
- for value in range(1,5):
print(value)
- var_list=list(range(1,5))
print(var_list)
- range(2,11,2)
#從2開始,不斷加2,一直達到或者超過11
- 列表解析
squares=[value**2 for value in range(1,11)] print(squares) # 輸出 [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
- list[0:3] # 返回索引0 1 2 元素
- list[:4] # 返回前4個元素
- list[2:] # 返回第三個到最後一個元素
- list[-2:] # 返回倒數兩個元素
- list[:] #複製列表;如果是list2=list1,只是將list2指針指向list1,並沒有真正複製創建一個新list
- 檢查一個值在不在列表中
var_list=["nihao","nihaoa","nizhendehao"] "nihao" in var_list "nibuhao" not in var_list
5 元組
- 不可變的列表
- 定義 ,嚴格的說元組是由逗號標識的,定義只包含一個元素的元組,也必須在這個元素後面加上逗號,所以 dimensions=200,50 也是可以的
dimensions=(200,50) #元組使用圓括弧 print(dimensions[0])
- 修改元組變數,雖然不能修改元組的元素,但是可以給存儲元組的變數重新賦值
dimensions[0]=250 # 這個是錯誤的 dimensions=(250,50) # 這個是合法的
6 字典
- 字典是一系列鍵值對,與鍵相關聯的值可以是數、字元串、列表乃至字典等任意一個Python對象。
var_dic={'color':'green','point':5} # 創建字典 print(var_dic['color'])
- 添加
var_kong_dic={} # 創建一個空的字典 var_kong_dic['nihao']="nihao" # 在字典中添加鍵值對 var_kong_dic['nibuhao']="nibuhao" print(var_kong_dic)
- 修改
var_kong_dic['nihao']="How are you?" # 修改值 print(var_kong_dic)
- 刪除
del var_kong_dic['nibuhao'] #刪除鍵值對 print(var_kong_dic)
- 獲取
point_value=var_kong_dic.get('point',"No point value assigned") #直接列印字典不存在鍵值報錯,get不存在時返回第二個參數;沒有指定第二個參數返回None print(point_value)
- 遍歷
# 添加幾個值做演示 var_kong_dic['cnihaos']="nihao"#在字典中添加鍵值對 var_kong_dic['anihaoss']="nihao"#在字典中添加鍵值對 for k,v in var_kong_dic.items(): print("Key:"+k) print("Value:"+v)
- 獲取字典 鍵的 列表 # 同樣的,值 values
print(var_kong_dic.keys()) print(type(var_kong_dic.keys()))
- 排序遍歷
for name in sorted(var_kong_dic.keys()): print(name)
- 刪除重複遍歷
for var_values in set(var_kong_dic.values()) print(var_values)
- 區別 集合
# 集合 不會以特定的順序存儲元素 var_jihe={'python','java','C#'} print(var_jihe) 字典 列表 alien_0={'color':'green','points':5} alien_1={'color':'red','points':10} alien_2={'color':'yellow','points':15} aliens=[alien_0,alien_1,alien_2] print(aliens)
7 函數相關
- input函數
- 讓程式暫停運行,等待用戶輸入並將用戶輸入賦值給一個變數,其參數是向用戶顯示的提示
message=input("Pleaseinputsomething:") print(message) # input獲取的都是字元串類型
- 強制類型轉換
age=input("Howoldareyou?\n") print(type(age)) print(":"+age) age=int(age) # 強制類型轉化 print(type(age)) print(":"+str(age)) # 輸入字元串+數字會報錯,所以還需要再來一次類型轉換
- 傳遞任意數量的實參
形參中的 * 讓Python創建一個空元組(不可變),並將收到的所有值都封裝在這個元組中、
defmake_pizza(*toppings): """"列印顧客所點的所有配料""" print(toppings) print(type(toppings)) make_pizza('peperoni') make_pizza('mushrooms','greenpepers','extracheese')
- 使用任意數量的關鍵字實參
- 形參中的 ** 讓Python創建一個空字典,將所有名稱值對都放在字典中
defbuild_profile(first,last,**user_info): """創建一個字典,其中包含我們知道的有關用戶的一切""" user_info['first_name']=first user_info['last_name']=last returnuser_info user_profile=build_profile('albert','einstein',location='princeton',field='physics') print(user_profile)
8 讀取/寫入 文件
- 讀取整個文件
#原文件中的換行會被讀取,但是列印末尾會多一個空行,因為read() 到達文件末尾時會返回一個空字元串,而將這個空字元串顯示出來就是一個空行,如果要去除空行,就在字元串末尾加一個 rstrip() with open("pi.txt") as file_object: contents=file_object.read() print(contents)
- 逐行讀取
#逐行讀取每行末尾都會有一個換行符,所以需要加一個rstrip去除 with open("pi.txt") as file_object: for line in file_object: print(line.rstrip())
- 創建一個包含文件各行內容的列表
with open("pi.txt") as file_object: lines=file_object.readlines() print(type(lines)) print(lines) print("\n") for line in lines: print(line.rstrip())
- 寫入空文件
# 這樣會覆蓋掉原文件中的內容,打開文件時的w參數,a 附加模式(在文件末尾添加不會覆蓋原內容),r+讀寫模式,省略參數默認r 只讀模式 with open("pi.txt",'w') as file_object: file_object.write("I love programming.") with open("pi.txt",'a') as file_object: file_object.write("\nI love programming,too.")
- json 存儲與讀取
import json numbers=[2,3,4,5,6,9] # 存儲 filename='numbers.json' with open(filename,'w') as f: json.dump(numbers,f) f.close() # 讀取 file_name2='numbers.json' #異常處理 try: with open(file_name2,'r') as f: read_number=json.load(f) except FileNotFoundError: print("The file is not found!") else: print(read_number) print(type(read_number))
9 測試
- 測試函數
- name_function.py
def get_formatted_name(first,last,middle=''): """形參中指定默認值得形參 middle只能放在最後""" if middle: full_name=f"{first}.{middle}.{last}" else: full_name=f"{first}.{last}" return full_name
- test_name_function.py
import unittest # 導入單元測試 from name_function import get_formatted_name class NameTestCase(unittest.TestCase): """繼承 unittest.TestCase""" def test_first_last_name(self): """方法名必須test打頭,這樣才能自動運行""" formaated_name=get_formatted_name("jone","json") self.assertEqual(formaated_name,"jone.json") """斷言方法""" def test_test_first_last_middle_name(self): formatteed_name=get_formatted_name("A","B","C") self.assertEqual(formatteed_name,"A.B.C") # 形參順序不對會報錯的 if __name__=='__main__': unittest.main()
- 測試類
- survey.py
class AnonymousSurvey: """構造函數""" def __init__(self,question): """存儲 問題和 答案的變數""" self.question=question self.responses=[] """顯示調查問卷""" def show_question(self): print(self.question) """存儲單份調查問卷""" def store_response(self,new_response): self.responses.append(new_response) """顯示所有答案""" def show_results(self): print("Survey Results:") for var_response in self.responses: print(f"-{var_response}")
- test_survey.py
-
# 導入單元測試 import unittest # 導入測試的類文件 from survey import AnonymousSurvey class TestAnonymousSurvey(unittest.TestCase): """使用setUp函數 創建一個所有方法都可以使用的類和答案列表""" def setUp(self): question="What language did you first learn to speak?" self.my_survey=AnonymousSurvey(question) self.responses=['English','Chinese','Janpanese'] def test_store_single_reponse(self): self.my_survey.store_response(self.responses[0]) self.assertIn(self.responses[0],self.my_survey.responses) def test_store_three_reponses(self): for reponse in self.responses: self.my_survey.store_response(reponse) for reponse in self.responses: self.assertIn(reponse, self.my_survey.responses) if __name__=='__main__': unittest.main()