# python 入門 ## 資料型態 **資料型態就是代表在變數間存放的資料的類別** >**數值型態:int, float, bool** 1.整數 integer(int) ex:-1, 0, 1, 2... x = 1 or x = int(input()) 此時在變數x裡的資料型態就是integer(int) 2.浮點數 floating-point (float) ex:-0.5, 1.11, 9.487... x = 1.5 or x = 1 / 2 此時在變數x裡的資料型態就是floating-point (float) 3.布林值 boolean (bool) ex:True, False x = True, x = bool(0) 此時在變數x裡的資料型態就是boolean (bool) >**字串型態:str, chr** 1.字串 string (str) ex:"dhdtht", "mathematics"... song = "Hello, Goodbye" 此時在變數song裡的資料型態就是string (str) 2.字元 character (chr) ex:'p', 'y', 't', 'h', 'o', 'n', '6'... c = 'c', c = '6' 此時在變數c裡的資料型態就是character (chr) >**容器型態:list, dict, tuple** ## 條件 1.if敘述 ``` if condition: statement 在關鍵字"if"後面放入一段敘述條件 若敘述成立,則下一行的statement會執行 ``` 2.if-else敘述 ``` if condition: statement1 else: statement2 若if後面的條件不成立,則statement2會執行 ``` 3.if-elif-else敘述 ``` if condition1: statement1 elif condition2: statement2 elif condition3: statement3 ................ else: statement 若if後面的條件不成立,則可使用elif繼續測試其他條件,若其條件成立,則該項statement會執行 elif可以放置的數量沒有上限 ``` ## 迴圈 1.for-loop ``` for i in sequence: #要執行的程序 變數i會代表sequence內的各個資料去一個個執行程序(也因此變數i不需要被定義) ``` Example:for ```python= sequence=(1,2,3,4,5,6) for i in sequence: print(i,"個人") ``` 執行結果 ![](https://i.imgur.com/Qwy61Hq.png) 2.break 和 continue break中斷迴圈然後讓迴圈結束 continue也會中斷迴圈但不會讓迴圈結束而是略過剩下的程序然後繼續執行下一次迴圈 Example:break ```python= sequence=(1,2,3,4,5,6) for i in sequence: if i == 4: #兩個等於的意思是完全相同 break print(i,"個人") ``` 執行結果 ![](https://i.imgur.com/3bTyMKK.png) Example:continue ```=python sequence=(1,2,3,4,5,6) for i in sequence: if i == 4: #兩個等於的意思是完全相同 continue print(i,"個人") ``` 執行結果 ![](https://i.imgur.com/YzuLhw3.png) 3.while-loop while expression: #要執行的程序 只要expression為True,迴圈就會繼續執行迴圈 Example ```python= people=0 while people<5: people=people+1 print(people,"個人") ``` 執行結果 ![](https://i.imgur.com/q4OuKvh.png) <!-- nested-loop要介紹太複雜了,他們大概也聽不懂,所以略過不介紹 --> ## 好用的函數 1.range() ``` range函數可以創造一整條整數列表,通常都用在for迴圈中 預設起點為0,間格為1,用法大概如下: 1.range(5)=[0,1,2,3,4] #從0開始到5的前一位 2.range(1,5)=[1,2,3,4] #從1開始到5的前一位 3.range(2,11,2)=[2,4,6,8,10] #從2開始,每個數字間都差2 4.range(10,0,1)=[10,9,8,7,6,5,4,3,2,1] #間隔可以是負數 ``` 2.abs() ``` abs函數可以拿來取絕對值,abs(x)=|x|。下面是一些例子: 1.abs(-20)=20 2.abs(123.45)=123.45 ``` 3.round() ``` round函數可以用來四捨五入到我們想要的位數,具體方法如下: > 如果沒有給指定位數的話,會自動四捨五入到整數部分,並返回最接近的整數 > 如果有指定位數的話,會依據指定位數的下一位>=5來進位或<5並捨去 example 1.round(15)=15 2.round(3.1)=3 3.round(4.8)=5 4.round(2.665,2)=2.67 #指定到小數第二位 5.round(2.7182,3)=2.718 #指定到小數第三位 ``` 4.eval() ``` eval函數用來執行一個表達式,並且回傳他的值,範例如下: 1.eval("3*4")=12 2.eval("5+8")=13 3.eval("abs(-6)")=6 ``` ## 產生(Generator) 比較進階的python語法,方式是將for迴圈與加入(append)串列(list)的的程式碼濃縮成一行,進而簡化程式 也可以加入(簡化)if的行數 ``` new_list = [運算式 for i in sequence] ``` 一般寫法 輸出1到輸入數字的平方,如果輸入數字超過10,輸出1到10的平方 ```python= num_list=[] #空串列 n = int(input("輸入整數:")) if n >10: n=10 for i in range(1 , n+1): #從1開始到n+1的前一位 num_list.append(i**2) #i**2意思是i^2(i的二次方)#append會把括號的東西放進序列(list) print(num_list) ``` ``` 輸入整數:5 [1, 4, 9, 16, 25] 輸入整數:12 [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] ``` 產生(Generator)寫法 ```python= n = int(input("輸入整數:")) num_list=[i ** 2 for i in range( 1 , n+1) if i < 11 ] print(num_list) ``` ``` 輸入整數:6 [1, 4, 9, 16, 25, 36] 輸入整數:11 [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] ``` 一行寫法 ```python= print([ i ** 2 for i in range( 1 , int(input("輸入整數:")) + 1) if i < 11]) ``` ``` 輸入整數:7 [1, 4, 9, 16, 25, 36, 49] 輸入整數:11 [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] ``` ## 輸入、輸出 1.print():用於列印括號內的東西 ``` ex: print('hello world') 程式執行後會輸出hello world 宣告 X=5,print(X) 執行後會輸出5 #注意,列印字串時需用 "" 或''框住,要同時列印變數和字串時須用 ',' 隔開 ex: x=2 print('我今天喝了',x,'杯飲料') ``` 2.input():用於輸入 ``` ex: x=input(),意思是將輸入的東西存在x這個變數裡 也可在括號內加入提示,ex: x=input("請輸入:"),執行時會先顯示括號內的字再進行輸入。 需要注意的是,輸入的資料會被預設為字串(str),因此需要轉換資料型態,ex: x=int(input()), 把x變成整數後才能用於運算。 ``` ## 字串 字串(string)是資料型態的一種,常以成對的引號來呈現,單引號、雙引號 、三個單引號、三個雙引號都可以拿來表示字串,代表文字的意思 'this' "is" '''a''' """string! """ a = "apple" 這個字串可以看成a是一個盒子,而此盒子有五個格子,分別編號 0 1 2 3 4 ,且裏面分別存者 a p p l e >範例程式 ```python= a = "apple" print(a[0]) print(a[1]) print(a[2]) print(a[3]) print(a[4]) ``` >輸出 ``` a p p l e ``` **string基礎語法** 1.轉義字元 轉義可以讓你轉換字串內某些字元的涵義,你只要在要轉義的字元前加上一個\就可以轉義了 如果我想宣告字串a裡面放 I say "rabbit"! 的字串,輸入下方程式碼 ```python= a = "I say "rabbit"!" print(a) ``` 會有語法錯誤 SyntaxError: invalid syntax 使用 \ 將字串內的 " 轉義即可正常運作 ```python= a = "I say \"rabbit\"!" print(a) ``` | 常見轉義字元 | 呈現結果 | | -------- | -------- | | \’ | 單引號’ | | \” | 雙引號” | | \n | 換行,\n後的內容會換到下一行 | | \t | 定位空格,一個tab鍵的空格 | | \\ | 反斜線\ | 2.串的切片 str[起點:終點:跳階] 起點預設是0,終點預設為字串的長度(len(a)),跳接預設為1。 >範例程式 ```python= a = "abcdefghijklmnopqrstuvwxyz" print(a[0]) # 印第0格 print(a[3:10]) # 印第(3~9)格 print(a[:-1]) #從頭印到最後倒數第二個 print(a[1::2])#從第一格開始到最後一格,每次跳兩格 print(a[-1::-1])#從最後一格開始,每次跳往前跳一格(倒者印) ``` >輸出 ``` a defghij abcdefghijklmnopqrstuvwxy bdfhjlnprtvxz zyxwvutsrqponmlkjihgfedcba ``` 3.字串操作 :::danger 字串是無法修改的,只能透過宣告新的變數來做到字串的修改 字串修改範例 ``` a = "123456789" a[3] = "a" ``` 會得到這個錯誤 ![](https://i.imgur.com/LYrk8DU.png) 我們必須這樣 ``` a = "123456789" b = a[0:3] + "a" +a[4:] print(b) ``` ::: 4.取得字串長度 >語法 ``` python= len(str) #括號中填入要取得長度的字串 ``` >範例程式 ``` python= str = 'hello python' print(len(str)) ``` >輸出 12 上方的例子中,空格也算一個位元,所以字串長度為12。 輸出 ``` 123a56789 ``` **string常用函式** 1.字元大小寫轉換 >範例 ```python= _str = "aPPle" #直接返回一個新的str大寫字串 print(_str.upper()) #直接返回一個新的str小寫字串 print(_str.lower()) #大小寫互換 print(_str.swapcase()) #將首字母變大寫 ,其餘的變成小寫 print(_str.capitalize()) #將字串 中的每個單詞的首字母變成大寫,其餘變小寫 print(_str.title()) print(_str) ``` >輸出 ``` APPLE apple AppLE Apple Apple aPPle ``` 2.頭尾刪除 >功能 將字串兩端的指定字元刪除 >語法 ``` python str.strip(chars) #chars 為指定字元,若沒寫則默認為空格字元 ``` >範例 ```python= str = "0000this is string example....wow!!!00000" print str.strip('0') ``` >輸出 this is string example....wow!!! 3.對齊 ```csvpreview 方法,功能 center(),依照括號內填入的數字,將字串於相對空格中置中對齊 rjust(),依照括號內填入的數字,將字串於相對空格中靠右對齊 ljust(),依照括號內填入的數字,將字串於相對空格中靠左對齊 ``` >範例程式 ```python= l = 'Quan'.ljust(10) c = 'Quan'.center(10) r = 'Quan'.rjust(10) print(l) print(c) print(r) l = 'Quan'.ljust(10,'*') c = 'Quan'.center(10,'*') r = 'Quan'.rjust(10,'*') print(l) print(c) print(r) ``` >輸出 ``` Quan Quan Quan Quan****** ***Quan*** ******Quan ``` 4.拆出多個字串 >功能 以指定字元來切割,並回傳包含分拆後各個字串的串列(list) >語法 ```python= str.split(chars) #chars 為指定字元,若沒寫則默認為空格字元 ``` >範例 ```python= str = "You\nwork\nvery\nhard!" print(str.split('\n')) ``` >輸出 ['You', 'work', 'very', 'hard!'] 5.replace() 回傳指定的部分會被替換後的字串,原本的字串不會改變。 >語法 ```python= str.replace(str1, str2) #str1為要被替換的字串,str2為要替換成的字串 ``` >範例程式 ```python= a ="the new skill I am learning this year : Python." print(a.replace("Python", "playing guitar")) print(lesson) ``` >輸出 ``` the new skill I am learning this year : playing guitar. the new skill I am learning this year : Python. ``` 6.搜尋 (1) count >功能 計算特定字串出現次數,回傳值為int >語法 ``` python str.count(string,start,end) #string 為要被數的子字串 #start 為尋找字串的起點 #end 為尋找字串的終點 ``` >範例程式 ```python= str = "0000this is string example....wow!!!00000"; print(str.count("0")); ``` >輸出 9 (2) index()、find() >功能 回傳子字串首個字母在字串中的位置 >語法 ``` python str.index(string) str.find(string) #string 為要被找的字串 ``` >範例程式: ```python= lesson ='the new skill I am learning this year : Python.' print(lesson.index('the')) print(lesson.find('the')) print(lesson.index('I')) print(lesson.find('I')) ``` >輸出: ``` 0 0 14 14 ``` 當找不到目標時呢?index() 方法會回覆 ValueError,find() 則回傳 -1。 使用find(): ``` lesson ='the new skill I am learning this year : Python.' print(lesson.find('peace')) #輸出-1 ``` 使用index(): ``` lesson ='the new skill I am learning this year :Python.' print(lesson.index('peace')) #結果 ValueError: substring not found ``` **補充 ASCII碼操作** >ord() 將字元轉成 ASCII 碼 ```python s = "ABCD" for c in s: print(f"{c} ASCII_code = {ord(c)}") ``` ``` A ASCII_code = 65 B ASCII_code = 66 C ASCII_code = 67 D ASCII_code = 68 ``` >chr() 將數字(int)轉成字元 ```python a = 88 b = 77 c = 66 print(f"{a} : {chr(a)}") print(f"{b} : {chr(b)}") print(f"{c} : {chr(c)}") ``` ``` 88 : X 77 : M 66 : B ``` ## 集合(set) set 物件是無序,即使你印出來時發現是按照順序的,所以在使用 set 時要記得不保證有序的 set 集合裡是不會包含重複的元素 set 用 {} 來包住元素 ```python= s1={1, 2, 3, 4, 5} s2={1, 1, 2, 2, 3} print(s1) print(s2) ``` ``` {1, 2, 3, 4, 5} {1, 2, 3} ``` 也可用 set() 來建構集合或空集合 ```python= s3 = set((2, 3, 1))#使用 set() 集合轉tuple的型態 s4 = set() s5 = {} print(s3) print(s4) print(s5) print(type(s3)) print(type(s4)) print(type(s5)) ``` ``` {1, 2, 3} set() {} <class 'set'> <class 'set'> <class 'dict'>#要注意s5是空字典而不是空集合 ``` 更多使用 set() 集合轉型的例子 ```python= student="student" print(set(student)) list1=[student,"1","2","r","3"] print(set(list1)) tup=(student,"1","2","r","3") print(set(tup)) ``` ``` {'u', 'e', 'd', 't', 's', 'n'} {'3', '1', '2', 'student', 'r'} {'3', 'student', 'r', '1', '2'} ``` len() 可判斷集合的元素數量 ```python= student="student" print(len(set(student))) list1=[student,"1","2","r","3"] print(len(set(list1))) tup=(student,"1","2","r","3") print(len(set(tup))) ``` ``` 6 5 5 ``` 利用集合(set)和序列(list)的轉換可以剔除掉相同、重複的數據,增加程式效率 ```python= n = 27720 div = 2 num = [] #空序列(list) while n > 1: if n % div == 0 : n //= div #n=n//div num.append(div) else: div += 1 print(num) num = list(set(num)) print(num) ``` 質因數分解,再利用 set() 質因數把挑出來 ``` [2, 2, 2, 3, 3, 5, 7, 11] [2, 3, 5, 7, 11] ``` ### 集合操作 ```csvpreview {header=true} 符號,說明,函數 &,交集,intersection() |,聯集,union() -,差集,difference() ^,動稱差集,symmetric_difference() ==,等於 !=,不等於 in,是成員 not in,不是成員 ``` ```python= A = {1,2,3,4,5} B = {4,5,6,7,8} print(A & B ,A | B,A - B,A ^ B) C = {1,2,3,4,5} D = {1,2,3} E = {4} print(A == B,A == C,A!=B,E in A,D in A) ``` ``` {4, 5} {1, 2, 3, 4, 5, 6, 7, 8} {1, 2, 3} {1, 2, 3, 6, 7, 8} False True True False False ``` 集合使用 add() 來加入新元素 記得 set 集合裡是不會包含重複的元素 ```python= s = {1, 2, 3, 4, 5} s.add(5) s.add(6) s.add(7) s.add(7) print(s) ``` ``` {1, 2, 3, 4, 5, 6, 7} ``` ### 集合方法(methods) ```csvpreview {header=true} 方法(method),說明 add(),增加一個元素到集合 clear(),清空集合 copy(),複製集合 discard(),從集合移除元素,如果元素不在集合內,它不做事 remove(),從集合移除元素,如果元素不在集合內,回報錯誤(回報KeyError) pop(),從集合移除第一個元素,並回傳(返回)被移除的元素(如果集合的順序是隨機的,被移除的元素也就不確定了) A.isdisjoint(B),如果2個集合(A和B)沒有交集則回傳(返回)True A.issubset(B),如果B集合包含A集合回傳(返回)True A.issuperset(B),如果A集合包含B集合回傳(返回)True A.update(B),回傳2個集合(A和B)的聯集給A集合 A.intersection_update(B),回傳2個集合(A和B)的交集給A集合 A.difference_update(B),回傳2個集合(A和B)的差集給A集合 A.symmetric_difference_update(B),回傳2個集合(A和B)的動稱差集給A集合 ``` .add() .clear() .copy() .discard() .remove() .pop() ```python= A = {1,2,3,4,5} A.add(6) print(A) A.clear() print(A) B = A.copy() A = {5,6,"Andy","Brian","Black","sus"} print(B,A) A.discard(6) print(A) A.remove(5) print(A) pop = A.pop() print(A,pop) ``` ``` {1, 2, 3, 4, 5, 6} set() set() {'Black', 'Brian', 5, 6, 'sus', 'Andy'} {'Black', 'Brian', 5, 'sus', 'Andy'} {'Black', 'Brian', 'sus', 'Andy'} {'Brian', 'sus', 'Andy'} Black ``` .isdisjoint() .issubset() .issuperset() ```python= A = {1,2,3,4,5} B = {3,4,5} print(A.isdisjoint(B),A.issubset(B),A.issuperset(B)) ``` ``` False False True ``` .update() .intersection_update() .difference_update() .symmetric_difference_update() ```python= A = {1,2,3,4} B = {3,4,5,6} C = {1,3,5,7} D = {2,4,6,8} E = {2,4,6,8} print(A,B,C,D) B.update(A) print(B) C.intersection_update(A) print(C) D.difference_update(A) print(D) E.symmetric_difference_update(A) print(E) ``` ``` {1, 2, 3, 4} {3, 4, 5, 6} {1, 3, 5, 7} {8, 2, 4, 6} {1, 2, 3, 4, 5, 6} {1, 3} {6, 8} {1, 3, 6, 8} ``` ## 串列(list) 用於儲存一連串有順序的資料,可修改、增減。串列的元素可以是數字、字串、布林值,也可以是另一個串列 ```python= list1 = [1,2,3,'hello world',[4,5,6],True] ``` len()可以顯示串列長度 ```python= print(len(list1)) ``` 輸出: ``` 6 其中的[4,5,6]雖然也是list,但它仍屬於list1的元素,因此list1的長度為6 ``` 如果要取得list裡的元素,可以在list的名稱後面加[index值],index值從前數到後由0開始依序增加,從後數到前由-1開始依序遞減 ```python= list1 = [1,2,3,'hello world',[4,5,6],True] print(list1[0]) print(list1[1]) print(list1[2]) print(list1[-1]) print(list1[-2]) print(list1[-3]) ``` 輸出: ``` 1 2 3 True [4, 5, 6] hello world ``` 如果要取得特定範圍的元素,可以使用 ``` list的名字[起始index : 終止index : 間隔] 其中終止值不包含本身,間隔為正,代表由前數到後,間隔為負則由後數到前 起始值空白則預設為0,終止值空白則預設到最後一個,間隔空白則預設為1 ``` ```python= list1 = [1,2,3,'hello world',[4,5,6],True] print(list1[0:4]) print(list1[1:]) print(list1[1:5:2]) print(list1[5:1:-2]) print(list1[1: :2]) print(list1[:3]) ``` 輸出: ``` [1, 2, 3, 'hello world'] [2, 3, 'hello world', [4, 5, 6], True] [2, 'hello world'] (不包含5) [True, 'hello world'] (不包含1) [2, 'hello world', True] [1, 2, 3] ``` 如果list的元素也是list(或是string),可以用2個[]來取得該元素的資料 ```python= list1 = [1,2,3,'hello world',[4,5,6],True] print(list1[3][0]) print(list1[3][1]) print(list1[3][2]) print(list1[4][0]) print(list1[4][1]) print(list1[4][2]) ``` 輸出: ``` h e l 4 5 6 ``` list常用函式 ``` 1. list1.append(object):新增元素到list1的後面(一次只能新增一個) 2. list1.extend(list2):新增list2的元素到list1的後面 3. list1.insert(x,object):在index x的地方插入新的元素 ``` ```python= list1 = [1,2,3,'hello world',[4,5,6],True] list1.append('how are you') print(list1) list2 = [11,66,'yes'] list1.extend(list2) print(list1) list2.insert(1,'hi') print(list2) list1.append(list2) print(list1) list2.insert(1,list1) print(list2) ``` 輸出: ``` [1, 2, 3, 'hello world', [4, 5, 6], True, 'how are you'] [1, 2, 3, 'hello world', [4, 5, 6], True, 11, 66, 'yes']# list2的'元素'被新增 [11, 'hi', 66, 'yes'] [1, 2, 3, 'hello world', [4, 5, 6], True, [11, 66, 'yes']]# list2'整個list'被新增 [11, [1, 2, 3, 'hello world', [4, 5, 6], True], 66, 'yes']# list1'整個list'插入 ``` list常用函式(2) ``` 1. list1.count(x):計算x在list1中出現的次數 2. list1.index(x):回傳x在list1的index值(有重複目標時,取小的) 3. list1.remove(x):刪除list1中的x 4. list1.pop(index):回傳該index的元素,並刪除該元素 5. list1.reverse():反轉list1的元素 6. list1.clear():完全清除list1的元素 ``` ```python= list1 = [1,1,1,1,1,2,2,2,2,2,3,3,3,3] print(list1.count(1)) print(list1.index(3)) list1.remove(2) print(list1) x = list1.pop(11) print(list1) print(x) list1.reverse() print(list1) list1.clear() print(list1) ``` 輸出: ``` 5 10 [1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3] #一次只刪除一個 [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3] 3 [3, 3, 3, 3, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1] [] ``` ## 元組(tuple) ``` tuple有以下特點: 1.tuple資料組建立之後,裏頭的資料就不可以再改變。 2.tuple資料組中的資料可以有不同的資料型態,甚至可以包含另一個資料組。 3.tuple資料組可以利用指定運算子把資料分配給多個變數。 4.tuple資料組顯示的時候,會用圓括弧( )把資料括起來。 ``` ### 建立元組 ``` tup = (a,b,c....) 裡面可以是任何的資料型態 ``` ### 修改元組 ``` tuple跟list最大的差別,就是無法隨意更改裡面的元素 Ex: tuple = (0,1,0,1) tuple[4] = 2 如果真的想要修改,則必須重新賦值 Ex: tup = (1,2,3) tup = (4,5,6) tuple跟list也能用tup()跟list()互相轉換 Ex: tup = (1,2,3,4,5) print(tup) ##(1,2,3,4,5) lis = list(tup) ##[1,2,3,4,5] lis.append(7) ##[1,2,3,4,5,7] print(lis) tup = tuple(lis) ##(1,2,3,4,5,7) print(tup) ``` ### tuple迭代 tuple也可以用for迭代 Ex: ``` tup = (1,2,3,4,5) for i in tup: print(i,end = " ") print() for i in tup[-1::-1]: print(i, end=" ") print() ``` Output: ``` 1 2 3 4 5 5 4 3 2 1 ``` ### enumerate & zip enumerate會幫忙把一個可迭代物件裡面的物件跟元素打包兩兩一組。每一組都是tuple型式,用法為: ``` enumerate(迭代物件,start=起始編號) ``` Ex: ``` data = ["A","B","C","D"] enumerate_data = enumerate(data) for t in list(enumerate_data): print(t) enumerate_data = enumerate(data,start=1) print() for t in list(enumerate_data): print(t) ``` Output: ``` (0, 'A') (1, 'B') (2, 'C') (3, 'D') (1, 'A') (2, 'B') (3, 'C') (4, 'D') ``` enumerate只能使用一次,第二次就不能使用了,除非重新宣告 打包還能用zip()函式 zip主要讓兩個以上的迭代物件做打包 Ex: ``` l1 = [1,2,3] l2 = ['a','b','c'] l3 = ['A','B','C'] h = zip(l1,l2,l3) print(list(zip(h))) ``` Output: ``` [((1, 'a', 'A'),), ((2, 'b', 'B'),), ((3, 'c', 'C'),)] ``` ## 字典(dictionary) 在python的字典當中,每一個元素都由鍵(key)跟值(value)所組成,結構為 key: value。 ### 建立字典 ``` 字典裡元素的"值"(value)可以是任何的資料型態, 例如: 字串、整數、list、物件等等。 但 key 必須是唯一且不可變的, 也就是在寫程式時不可隨意更動,如整數、字串、tuple 等。 ``` 建立方式有兩種,包含使用{}和內建函數dict() ``` my_dictionary1 = {"element1": "honey", "element2": "sugar"} my_dictionary2 = dict(element1 = "tea", element2 = "coffee") Peter = {"age": 16, "gender": "male", "sport": "soccer"} ``` ### 獲取value 建立字典以後,可以使用下列方式來獲取key的value ``` print(my_dictionary1["element1"]) #得到"honey" print(my_dictionary2["element2"]) #得到"tea" print(Peter["gender"]) #得到"male" ``` 執行結果 ``` honey tea male ``` 如果輸入了不存在的key,程式會回傳錯誤的訊息 輸入: ``` print(Peter[school]) #school並不存在於"Peter"這個字典中 ``` 輸出: ``` KeyError: 'school' ``` 也可以使用get ``` print(Peter.get("age")) print(Peter.get("school")) #此時如果key不存在,程式便會輸出"None" ``` ### 新增或更新資料 用法如下: ``` dictionary[key] = value #key為新的鍵,其value為新的key所對應的值 ``` 舉例: ``` Peter[country] = "Taiwan" #此時Peter這個字典就多了"country"這個key, 其所對應的value便是"Taiwan" ``` ### 刪除資料 要刪除一筆元素,有兩種方式: #### 1.del method 使用del敘述來刪除一筆key-value元素,其中括號裡數入的是key: ``` del Peter["sport"] #此時"sport"就不存在於Peter這個字典內 ``` #### pop method 如果想刪除Peter裡的key-value,同時回傳該數值,可以用pop: ``` sport = Peter.pop("sport") print(Peter) print(sport) ``` 輸出: ``` {age: 16, "gender": male, "country": "Taiwan"} soccer #下面一行的soccer是已被刪除的key-value ``` ### 其他用法 #### 1.獲取字典中的元素個數 使用len()可回傳: ``` print(len(my_dictionary1)) print(len(Peter)) ``` 輸出: ``` 2 3 #Peter中包含了"age"、"gender"和"country",而"sport"已被刪除 ``` #### 2.印出字典中所有的key 使用keys(): ``` print(Peter.keys()) ``` 輸出: ``` dict_keys(['age', 'gender', 'country']) ``` #### 3.印出字典所有的value 使用values(): ``` print(Peter.values()) ``` 輸出: ``` dict_vals([16, 'male', 'Taiwan']) ``` #### 4.印出字典的所有元素 使用items(): ``` print(Peter.items()) ``` 輸出: ``` dict_itmes([('age', 16), ('gender', 'male'), ('country', 'Taiwan')]) ``` #### 5.檢查指定的key是否存在於字典裡 使用 in: ``` print("gendre" in Peter) print("school" in Peter) ``` 輸出: ``` True False #"school"並不存在於Peter中 ```