--- title: 'Python學習筆記' disqus: hackmd --- Python 學習筆記之路 Part.2 = > 上一回講了基礎數據類型、邏輯判斷、迴圈...等 > 詳情請見第一回:https://hackmd.io/@wr2rCYhVRSeVzSIPcixIiQ/Hk5UQ9b-a > 此回要接續上篇,著重介紹:函數製作、 目錄 == [TOC] 函數製作 == > 利用for迴圈遍歷每一個變數內的字母,並且每遍歷一個字母就紀錄一次,如此一來就能夠自製一個len函數 ```gherkin= # 不使用內置函數,寫出len str1 = "itheima" str2 = "itcast" str3 = "Python" count = 0 for i in str1 : count+= 1 print(f"字符串str1, 裡面字符的長度為{count}") ``` > 倘若每一次我們都要重新寫一次for迴圈是相當麻煩的一件事情,所以我們可以自己創建一個函數,這樣調用我們想要的函式就不用每次都重新寫一次迴圈 > 語法: > >def 函數名稱(參數): > >>函式 ### 範例1: ```gherkin= # 進行製作函數 def my_len(data): count = 0 for i in data: count+= 1 print(f"字符串str1, 裡面字符的長度為{count}") my_len(str2) ``` ### 範例2: ```gherkin= # 自製兩數相加 def add(x,y): result = x + y print(f"{x}+{y}的計算結果是:{result}") add(3, 4) ``` ### 練習1: ```gherkin= # 製作函數,以37.5度為發燒,製作溫度計 def temp(x): if x <= 37.5: print(f"您的體溫是{x}度, 體溫正常請進") else: print(f"您的體溫是{x}度, 你確診了拉哭喔") temp(37) ``` 函數製作2 == > 函數返回值 return > return x ,將x這個變數回傳 就是在程式中結束的結果, 最後交給使用者的結果 遇到return, 後面的程式碼都不執行 ```gherkin= def add(x,y): result = x + y return result print("我結束了") #return後的值不執行 r = add(5, 6) print(r) ``` > return 返回值None > None表示空的, 沒有實際意義的意思 ```gherkin= def say_hi(): #不寫return自動返回none值 print("你") result = say_hi() print(type(result)) ``` ### None的應用 > None可以實際應用在 1.函數只做事不回傳值 2.用在if判斷上的話,None指的是False 3.暫時不需要具體變數值得時候可以使用 ```gherkin= def CA(age): if age >18: return "sucess" else: return result = CA(19) # 將CA()內的數字改成19以內可看出None在IF上的邏輯判斷 if not result: print("你是未成年") print(f"{result}") ``` 函數的註解 == > 有時候我們雖然定義完函式,但函式、參數一多,有時候還要去查看原函式如何使用...等非常麻煩,所以我們可以對函式進行註解,讓我們知道每個參數代表的意義 ```gherkin= def add(x,y): ''' add可以接收2個函數, 進行兩數的相加 :param x:第1個參數 :param y:第2個參數 :return: ''' result = x + y print("我結束了") #return後的值不執行 return result add(x,y) # 把滑鼠移到上頭,就可以知道目前函式參數的解釋 ``` 函數的調用 == >有時候我們寫完一個函式了,我們可以在【新函式】內,寫上其他函式進行調用 ### 一般調用: ```gherkin= def func_b(): print("---2---") def func_a(): print("---1---") func_b() print("---3---") func_a() ``` ### 局部變數與全局變數 > 所謂局部變數意思為只在函數內才會作用的變數 > 從外部呼叫是沒有用的 #### 局部變數: ```gherkin= # 在函式外呼叫了函式內的變數 # 會顯示Error def test_a(): num = 100 print(num) test_a() print(num) ``` #### 全局變數: > 無論在函數內部或外部都能生效的變數 若你同時在a, b, c...等function都要使用的話,就在函數外定義變數 這樣就可以從內部呼叫外部變數進行分析 ```gherkin= num = 200 # global variable def test_a(): print(num) def test_b(): print(num) ``` > 若在函式內想要用相同名稱引用變數 可以在函式內部定義變數,就可以在"函數內部"修改 ```gherkin= num = 200 def test_a(): print(num) def test_b(): num = 500 print(num) test_a() test_b() ``` > 若想要在函數"內部" 修改 "全局"變數 可以使用global變數 在使用變數前在上面加上global,就可以透過局部變數直接修改全局變數 ```gherkin= num = 200 def test_a(): print(num) def test_b(): global num num = 500 print(num) test_a() test_b() print(num) # 將全局200改成了500 ``` #### 綜合練習題: 請利用自製函式及函式調用,製作一台ATM機器,並列出以下內容 > 請輸入您的大名123 請輸入密碼123 123你好, 歡迎來到黑馬銀行ATM, 請選擇您的操作: 查詢餘額 [輸入1] 存款 [輸入2] 取款 [輸入3] 退款 [輸入4] _________________________ 請輸入您的選擇1 --------查詢餘額--------- 123您好, 您的餘額剩下:5000000元 __________________________ 請輸入您的選擇2 123您好,您要存入多少錢?1 123 您好,您存款1元成功 --------存款-------- 123您好, 您的餘額剩下:5000001元 __________________________ 請輸入您的選擇3 123您好,您要提款多少錢?1 123您好,您提款1元成功 --------存款-------- 123您好, 您的餘額剩下:5000000元 __________________________ 請輸入您的選擇4 123,銀行功能尚不支援退款功能,請稍後插卡 >解答: ```gherkin= account = 5000000 def machine(): global account #使用global變數應該要在先前就聲明,在定義就先表明 user_name = input("請輸入您的大名") user_password = input("請輸入密碼") print(f"{user_name}你好, 歡迎來到黑馬銀行ATM, 請選擇您的操作:\n" "查詢餘額 \t[輸入1]\n" "存款 \t[輸入2]\n" "取款 \t[輸入3]\n" "退款 [輸入4]") choose = int(input("請輸入您的選擇")) if choose == 1: print("--------查詢餘額---------" f"\n{user_name}您好, 您的餘額剩下:{account}元") elif choose == 2: deposite = int(input(f"{user_name}您好,您要存入多少錢?" )) print(f" {user_name} 您好,您存款{deposite}元成功") account += deposite print("--------存款--------" f"\n{user_name}您好, 您的餘額剩下:{account}元") elif choose == 3: withdraw_money = int(input(f"{user_name}您好,您要提款多少錢?" )) print(f"{user_name}您好,您提款{withdraw_money}元成功") account -= withdraw_money print("--------存款--------" f"\n{user_name}您好, 您的餘額剩下:{account}元") else: print(f"{user_name},銀行功能尚不支援退款功能,請稍後插卡") machine() ``` 數據容器 == ## List 列表 #### List 我們能夠在List裡面再放入List 其類型依舊為List ```gherkin= name_list = ['itheima', 'itcast' ,' python'] print(name_list) my_list = [[1,2,3],[4,5,66]] print(my_list) print(type(my_list)) ``` #### 取出list中的元素 list中的元素是有順序的(具有index性質) 正序從0開始, 倒序從-1開始 list可以用-1,-2...從最後一個、倒數第二個反向取出 ```gherkin= name_list = ['tom', 'amy', 'potter'] print(name_list[1]) print(name_list[-1]) ``` > 若list中還有一個list 那可以先把裡頭list的狀態看成1個elements 取出該elements後再看成list,之後再取出對應位置即可 現在要取5這個元素 >先取外層index為1的list,取出該list後再取出index為1的元素 ```gherkin= my_list = [[1,2,3],[4,5,6]] print(my_list[1][1]) ``` #### 查找index ```gherkin= mylist = ['itheima', 'itcast', 'python'] index = mylist.index('itheima') print(index) ``` #### 修改指定index內的元素內容 ```gherkin= mylist = ['itheima', 'itcast', 'python'] mylist[0] = "podcast education" print(f"列表被修改元素後, 結果是:{mylist}") ``` ### 加入元素 #### 列表中直接插入元素 語法:列表名稱.insert(列表下標,元素) 意思為:「在列表的指定位置插入指定元素」 示範: 想在itcast 與 itheima中間插入一個best元素 ```gherkin= mylist.insert(1, "best") # 在itcast與itheima中間插入後,該元素位置變為1,所以index打1 print(f"列表元素插入後, 結果是{mylist}") ``` #### 追加元素 語法:列表.append(元素), 將指定元素, 追加到列表的"尾部" insert需要指定位置, 而append只要給元素即可 ```gherkin= mylist.append("我超棒") print(f"列表在最後又追加一個元素的結果是:{mylist}") ``` #### 追加元素至尾部 語法:列表名.extend() ```gherkin= mylist2 = [1,2,3] # mylist.extend(mylist2) mylist.extend([4,2,3]) print(mylist) ``` ----------------------- ### 刪除元素 能夠增加也就能夠刪除元素 >語法1: del 列表名[index] 語法2: 列表名.pop(index) pop其實是將列表中的元素取出, 再利用賦予變量名稱得到該元素 ```gherkin= del mylist[2] print(mylist) elements = mylist.pop(2) print(elements) ``` #### 直接針對某個元素進行刪除 ```gherkin= mylist = ['itheima','itheima','itheima', 'itcast', 'python'] mylist.remove('itheima') print(mylist) ``` #### 一次清空全部元素 ```gherkin= mylist.clear() print(mylist) ``` ------------------------------- ### 計算元素個數 #### 統計某元素在列表內的數量 > 語法:列表.count(元素) ```gherkin= mylist = ['itheima','itheima','itheima', 'itcast', 'python'] count = mylist.count("itheima") print(count) ``` #### 計算此列表內總共有多少元素個數 > 重複名稱也算 ```gherkin= print(len(mylist)) ``` ## tuple #### tuple(元組)的定義格式 #### list的特點是可以被修改 #### tuple一旦定義完成就不能被修改 #### 通常用於不想被竄改數據 >語法: variable1 = () variable2 = tuple() ```gherkin= t1 = (1, "Hello, " ,True) t2 = () t3= tuple() print(f"t1的類型:{type(t1)}, 內容是{t1}") print(f"t2的類型:{type(t2)}") print(f"t3的類型:{type(t3)}") # 特別注意,若只有一個element, 那你的tuple後面需要加一個逗號"," # 沒有的話就變成str t4 = ("hello") t5 = ("hello",) print(type(t4)) #類型為str print(type(t5)) #類型為tuple ``` #### tuple裡放tuple ```gherkin= t5 = ((1,2,3),(4,5,6)) print(type(t5),t5) print(t5[1][2]) ``` #### index、count、len用法 > index ```gherkin= t6 = ("podcast education", "heima programmer", "Python") index = t6.index("Python") print(f"在tuple中查找Python在哪, 他的index是{index}") ``` > count ```gherkin= t7 = ("podcast education", "heima programmer", "Python", "Python", "Python", "Python") index = t7.count("Python") print(f"在tuple中Python的數量為:{index}") ``` > len ```gherkin= print(len(t7)) ``` #### tuple的遍歷 ```gherkin= # while index = 0 while index < len(t7): print(f"tuple的元素有: {t7[index]}") index +=1 # for for i in t7: print(f"tuple的元素有: {i}") ``` #### tuple小技巧 關於tuple有個小技巧 我們知道不能修改tuple的內容, 但可以修改list裡面的 我們知道list裡面可以再放list, 也能夠再放tuple 反過來也一樣, 可以在tuple裡面再放tuple或list 所以我們可以修改tuple裡面的「list」 舉例: ```gherkin= t9 = (1,2,3,[4,5,6]) print(f"t9裡面的內容是:{t9}") t9[3][1]="我愛Python" print(f"t9裡面的內容是:{t9}") # #如此一來我們就將list裏頭5的位置改成了我愛Python ``` #### 練習題 有四個欄位 | 名稱 | 年齡 | 運動愛好 | 興趣 | | -------- | -------- | -------- | --- | | 鄒杰人 | 11 | football | music | 要求: 1.創建一個tuple放入以上欄位,後面兩個欄位用list 2.找出年齡所在欄位 3.取出名字 4.刪除music元素 5.將coding重新加入原本music元素的位置 > 解答 > ```gherkin= pratice_tuple = ('鄒杰人',11,["football",'music']) index = pratice_tuple.index(11) print(f"年齡index的所在位置為: {index}") name = pratice_tuple[0] print(f"學生姓名為:{name}") del pratice_tuple[2][1] name, age, habbit = pratice_tuple habbit.append("coding") new_pratice_tuple = (name, age, habbit) print(new_pratice_tuple) ``` ## str 字符串 > str也能夠扮演數據容器角色 ```gherkin= my_str = "itheima and itcast" # index方法 value = my_str[2] value2 = my_str[-16] print(f"從字符串{my_str}取下標為2的元素, 其值是: {value}, 取下標為16的值是:{value2}") ``` > str也是不能夠修改其內容的 ```gherkin= my_str[2] = "H" ``` #### 字符串的index方法 >特別注意,中間空白的地方也會占用一格空間 ```gherkin= my_str = "itheima and itcast" my_str_1 = "itheimaand itcast" value1 = my_str.index("and") value2 = my_str_1.index("and") print(value1,value2) ``` #### 字符串的替換 >語法:字符串.replace(字符串1, 字符串2) 功能:將字符串內的全部內容:字符串1, 全數修改為字符串2 注意:不是修改字符串本身,而是得到一個新的字符串 ```gherkin= my_str = "itheima and itcast" new_my_str = my_str.replace("it", "城市") print(my_str, new_my_str) ``` #### 字符串的分割 >語法:字符串.split 將指定的分隔字符串,將多個字符串劃分為多個字符串, 並存入列表當中 ```gherkin= my_str = "hello python itheima itcast" my_str_list = my_str.split(" ") print(f"將字符串{my_str}進行分割後, 得到新的列表為{my_str_list}, 類型是{type(my_str_list)}") ``` ---------------------------- #### 字符串的排版(整規) 操作 功能1 >語法:字符串.strip() 作用:去除前後空格 ```gherkin= my_str = " itheima and itcast " new_my_str = my_str.strip() # 不傳入參數就是去除首尾空格 print(f"將字符串{my_str}進行strip分割後, 得到{new_my_str}, 類型是{type(new_my_str)}") ``` 功能2 >語法:字符串.strip(字符串) 作用:去除前後指定字符串 ```gherkin= my_str = "12itheima and itcast21" new_my_str = my_str.strip("12") # 傳入參數就是去除參數內的數據,是去除"1"、"2" print(f"將字符串{my_str}進行strip分割後, 得到{new_my_str}, 類型是{type(new_my_str)}") ``` #### 練習 > 在itheima itcast boxuegu中有2個it單字 將itheima itcast boxuegu中所有空格,更替為itheima|itcast|boxuegu ```gherkin= my_str = "itheima itcast boxuegu" print(f"在{my_str}中有{my_str.count('it')}個it單字") print(f"將{my_str}中所有空格,更替為{my_str.replace(' ','|')}") ``` ## sequence 序列 常用操作:切片 從序列裡得出一個子序列 用途:從序列中,從指定位置開始, 依次取出元素, 直到指定位置結束, 得到一個新序列 開頭是從0開始 得到的是一個新序列,對原本序列沒有影響 開頭可以留空,表達從頭開始;結尾也可以留空,表達取到結尾 如果說你在結尾寫到5,那數據是不包含5那個data本身的 > 語法:序列[inital index : ending index : step] ```gherkin= # 對list進行切片 # 想要從index為1一路取到3(並不包含indx下標為4) my_list = [0,1,2,3,4,5,6] print(my_list[1:4]) ``` > 如果要全拿就在中間打上分號 ```gherkin= # 對tuple進行切片 my_tuple = (0,1,2,3,4,5,6) print(my_tuple[:]) ``` > 從index為0開始一路到3,以每兩個index為基準取 ```gherkin= # 對str進行切片 my_str = "01234567" print(my_str[0:3:2]) ``` > 反轉術式!!!! ```gherkin= # 對str進行切片, 從頭開始, 到最後結束, 步長為-1 print(my_str[::-1]) #等同將序列反轉 # 對list進行切片, 從3開始, 到1結束, 步長為-1 print(f"結果為:{my_list[3:1:-1]}") ``` 將字體反轉,並且印出下列文字 > 來清華大學 來淡江大學 ```gherkin= ## 練習題 heima_list = "萬過薪月, 學大華清來, nohtyP學" positive_list = heima_list[::-1] print(positive_list[9:15]) heima_list = "萬過薪月, 學大江淡來, nohtyP學" print(heima_list.split(", ")[1][::-1]) ``` ## set 集合 集合具有不重複的性質,也就是相同元素在Set只會被看做一個,無論你記錄了多少個都一樣 ```gherkin= my_set = {"podast", "heima", "it","podast", "heima", "it","podast", "heima", "it"} my_set_empty = set() print(f"my_set的內容是{my_set}, 類型是:{type(my_set)}") print(f"my_set的內容是{my_set_empty}, 類型是:{type(my_set_empty)}") ``` #### 添加新元素 > 已經在集合裡頭的元素不會再被新增 ```gherkin= my_set.add("Python") my_set.add("it") print(my_set) ``` #### 移除元素 ```gherkin= my_set.remove("heima") print(my_set) ``` #### 清空集合 ```gherkin= my_set.clear() print(my_set) ``` #### 取集合的差集 > 會重新造出一個新的集合 ```gherkin= set1 = {1,2,3,6} set2 = {1,3,6} set3 = set1.difference(set2) print(set1,set2,set3,type(set3)) ``` #### 去除交集 > 語法:集合1.difference_update(集合2) 功能:對比集合1與集合2, 在集合1內, 刪除和集合2相同的元素會造成集合1裡面的內容被修改, 而集合2不會變 ```gherkin= set1 = {1,2,3,6} set2 = {1,3,6} set4 = set1.difference_update(set2) # 特別注意!因為是修改set1內的內容,不會輸出新variable,所以用這種模式寫,不會列出 # 任何東西 print(set4) print(set1) ``` #### 合併集合 > 語法:集合1.union(集合2) 功能:將集合1與集合2組成新集合 ```gherkin= set1 = {1,2,3,6} set2 = {1,3,6,7} set3 = set1.union(set2) print(set3) ``` #### 統計元素個數 > 統計集合元素個數 利用len而不是count是因為元素是去重複化的 ```gherkin= print(len(set1)) ``` #### 集合的遍歷 > 無法用while循環,因為沒有index 可用for循環 ```gherkin= set1 = {1, 2, 3, 4, 5} for x in set1: print(x, end = '') ``` #### 練習題 1.建立一個空集合用來存放元素 2.將空集合中重新放入列表的元素 3.將結果印出 > 列表元素['Pyhton新手', '你好podcast', 'Python新手', '你好podcast','itheima','itcast','itheima','itcast','best'] > 存入集合後的結果為:{'Python新手', 'itcast', 'itheima', '你好podcast', 'Pyhton新手', 'best'} ```gherkin= my_list = ['Pyhton新手', '你好podcast', 'Python新手', '你好podcast','itheima','itcast','itheima','itcast','best'] # 1 emptyset = set() # 2 for x in my_list: print(x, end =' ') emptyset.add(x) print(f"存入集合後的結果為:{emptyset}") ``` ## dict 字典 語法:利用{}就可以, {key:value, key:value} > 也可用dict() > dict不允許重複 所謂key就是關鍵訊息、value就是你想賦予他的值 #### 定義字典與空字典 ```gherkin= # 定義dict my_dict = {"王聰明": 99 , "吳清芬": 88} # 定義空dict my_dict2 = {} my_dict3 = dict() print(f"字典1的內容是:{my_dict}") print(f"字典2的內容是:{my_dict2}") print(f"字典3的內容是:{my_dict3}") ``` #### 字典也具去重複性 ```gherkin= my_dict_3 = {"王聰明": 99 , "吳清芬": 88, "吳清芬": 89} print(my_dict_3) ``` #### 通過key去獲得對應的value值 ```gherkin= my_dict_3 = {"王聰明": 99 , "吳清芬": 88, "王張三": 89} score = my_dict_3["王張三"] print(score) score2 = my_dict_3["王聰明"] print(score2) ``` #### 字典中再度放入字典 ```gherkin= # dict中的key和value可以是任意數據類型,但key不能夠是dict stu_score_dict = { "王張三":{ "語文":77, "數學":88, "英文":33}, "吳清芬":{ "語文":88, "數學":86, "英文":55}, "陳老師": { "語文":99, "數學":96, "英文":66} } print(f"學生的考試訊息{stu_score_dict}") # 查看吳清芬的考試訊息 chouscore = stu_score_dict["吳清芬"]["語文"] print(chouscore) # 查看陳老師的考試訊息 linscore = stu_score_dict["陳老師"]["英文"] print(linscore) ``` #### 字典元素的更迭 dict新增元素/dict更改元素 > 語法:dict[key] = value 語法相同怎麼辨識呢? 若你的字典不存在這個key, 那就會新增一個value 若你的字典存在這個key, 那就會將本來key的value值更替為你所新增的value值 ```gherkin= my_dict = {"王聰明": 99 , "吳清芬": 88, "王張三": 89} my_dict["李嗣"] = 66 print(f"字典經過更新後, 結果為{my_dict}") # 更改字典 my_dict["吳清芬"] = 33 print(f"字典經過更新後, 結果為{my_dict}") ``` #### 刪除字典中元素 ```gherkin= score = my_dict.pop("吳清芬") print(f"字典中被移除了一個元素, 結果:{my_dict}, 被移除的是{score}") ``` #### 清空字典 ```gherkin= my_dict.clear() print(f"被清空後的字典結果為:{my_dict}") ``` #### 一次獲取dict中每個key > 得到所有key可以幹嘛? 依次取得key, 能夠遍歷並得到依次得到所有的value值 ```gherkin= my_dict = {"王聰明": 99 , "吳清芬": 88, "王張三": 89} keys = my_dict.keys() print(f"這次考試中, 所有人的訊息是{keys}") ``` #### 遍歷字典 ```gherkin= # Way1: 通過獲取到全部的key來完成遍歷 for x in keys: print(f"字典的key是{x}") print(f"其value是{my_dict[x]}") # Way2: 直接對dict 進行for循環, 每一次循環都是直接得到key for i in my_dict: print(f"字典的key是{i}") print(f"其value是{my_dict[i]}") # 統計字典元素(key)數量 print(len(my_dict)) ``` ## 黑馬練習題(修改名稱) 將員工的列表輸入並完成修改 >1.將員工姓名、隸屬部門、工資、級別寫入字典 >2.將當前員工資訊印出 >3.若員工等級為1級,往上升級1級,並且工資+1000元 >4.印出張三、陳六的工資與級別 ```gherkin= employee_dict = { "張三":{ "部門" : "教育部", "工資" : 3000, "級別" : 1}, "李四":{ "部門" : "國防部", "工資" : 5000, "級別" : 2}, "王五":{ "部門" : "國防部", "工資" : 7000, "級別" : 3}, "陳六":{ "部門" : "教育部", "工資" : 4000, "級別" : 1}, "林七":{ "部門" : "國防部", "工資" : 6000, "級別" : 2} } print(f"當前員工的訊息如下{employee_dict}") for i in employee_dict: if employee_dict[i]["級別"] == 1: # 修改員工訊息 employee_dict[i]["級別"] += 1 employee_dict[i]["工資"] += 1000 print(employee_dict["張三"]["工資"], employee_dict["張三"]["級別"], employee_dict["陳六"]["工資"], employee_dict["陳六"]["級別"]) ``` ## 結語 目前將筆記又小小的推進了一部分: 從函數製作到數據容器花了一段時間整理與閱讀,比起第一次學程式,更多是在如何整理程式碼,但學起 來比第一次快的多。看著筆記一份份完善真的是很開心。 下次將會進行數據大小的比較、轉換開始,接著進行文件的處理,但文件處理蠻長的,有可能額外單獨紀 錄一份。 :::info **Find this document incomplete?** Leave a comment! :::