# Python 基礎教學 <!-- ## 個人網站 [click me](https://laicharlie.github.io) --> ## 變數型態 ### int int就是integer(整數)的縮寫 可以與float做加減乘除類的運算 也可以與String相乘(在String的部分會說明) ``` x = 1 print(type(x)) Output : <class 'int'> ``` > **Note :** 在 python 中,int 的範圍是沒有極限的,所以進行大數運算不需要考慮範圍 #### int補充 我們在Python中通常是以十進制(decimal)來表達int 但Python也讀得懂2進制、8進制與16進制 以下直接舉例說明 ``` # 0b : 2進位(binary) # 0o : 8進位(octal) # 0x : 16進位(hexadecimal) x = 0b0010 print(x) # 0b代表進位法,0010在二進位中 = 十進位的2 # 0後面的英文大小寫都可 : (0B0010=0b0010) Output : 2 ``` **Note:** 在Python中,井字號(#)是註解的意思 註解的程式碼是不會被執行的!!! 如果要一次註解多行的話,可以利用鍵盤快捷鍵 > 反白想註解的行數: > Windows:同時按下 control 與 / > MacOS:同時按下 command 與 / > **Note:** 若是單行註解則不需要反白 ### float 在Python中,帶有小數點的數字都屬於float 在下面的例子中,如果我們將整數加上1.0時 y的資料型態就變成float 是因為1.0是float的資料型態 **Note:** 在Python裡, 1. 就是1.0的意思,同理 .1 就是0.1 ``` x = 1 y = x + 1. print(type(y)) Output : <class 'float'> ``` ### string String是字串的意思 在Python的語法裡,字串可以用兩種方式表達 : ``` # First : str = "I am String" # Second : str = 'I am String' ``` Python的語法,用 "" 或 '' 都是可以的 Python中的String也支援加法跟乘法 用法: 1.加法:String1 + String2 (加號兩邊的資料型態都必須是String) 2.乘法:int * String or String * int (乘號兩邊必須是int與String) ``` str1 = "I am " str2 = 'String' temp = 3 print(str1+str2) print(temp*str1) print(str2*temp) Output : I am String I am I am I am StringStringString ``` 若是想一次輸出多行,也可以利用 """ 來實現 範例: ``` str = """ I AM PYTHON PROGRAMMER """ print(str) Output : I AM PYTHON PROGRAMMER ``` ### bool bool資料型態很簡單,只有兩種類型:True 跟 False **Note : T 跟 F 都要大寫** ``` cmp = 1 > 0 print(cmp) print(type(cmp)) Output : True <class 'bool'> ``` bool也可以與int的資料型態相互轉換: bool 轉 int: True 會轉換成 1 , False 轉換成 0 ``` cmp = False x = int(cmp) print(cmp) print(x) Output : False 0 ``` int 轉 bool: **所有非0的數**都會轉成True , 只有0會轉成False **Note**: **所有非0**的float也都可以轉換成True ``` cmp = -1 T = bool(cmp) print(T) print(type(T)) Output : True <class 'bool'> ``` ### 變數宣告 在Python中,變數宣告的語法非常簡單 變數名稱 = value 以下是幾個例子 ``` x = 1 y = 1. z = .1 str = "1" cmp = (1 > 0) # cmp = True ``` > 在設定變數名稱時有三點需要特別注意: > 1.不能用Python設定的Keyword > 2.不能有空白(可以用底線) > 3.不能以數字開頭 #### Keyword Keyword是Python內建帶有特殊意義的字串(String) ``` KeywordList : 'False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield' ``` ## 函式介紹(function) Python中,function大致分為兩種: 1.內建好的(build-in function) 2.開發者自訂(Definition by programmer) > 用法: > functionName() > 括號內為傳入function的參數,也可以不傳入任何參數 **Note :** function執行完後通常會return value (也可以不回傳任何資料) > **補充:** > method : function的一種,是屬於特定物件的function > 用法: > objectName.method() 現在先介紹 build-in function build-in function 是Python已經內建好的function 不需import任何module即可使用 ### print() Python內建的輸出函式 在print()括號內的資料皆會輸出 可以輸出幾乎所有資料型態:int, float, bool, string, dictionary, list, tuple, ... 接下來看例子來學習用法: ``` print("Hello World!") print("Hello" , "World!") #超過一個資料需要輸出時,需要用','來分隔 Output : Hello World! Hello World! ``` **Note :** 換行字元:'\n' 用法:直接加在字串中即可 ``` print("Hello\nWorld\n!") # print("Hello" + "\n" + "World" + '\n' + '!') #(輸出與第一行相同) # print("Hello" , "World" , '!' , sep='\n') #(輸出與第一行相同) Output : Hello World ! ``` **sep , end 用法:** ``` # sep 只會在超過一個data要輸出時起作用 # 用法 : 在想輸出的data後加上 sep= "" # example : print("Hello" , "World!",sep = "--") Output : Hello--World! ``` ``` # end 設定輸出結束後輸出的字串 , 預設為'\n'(換行字元) # 用法 : 在想輸出的data後加上 end= "" # example : print("Hello" , "World!",end = "--") print("~~~~") Output : Hello World!--~~~~ ``` **同時使用 end & sep** **Note :** sep與end之間的順序不影響輸出結果 ``` sepstr = "--sep--" print("Hello","World!" , end = "--\n" ,sep = sepstr ) Output: Hello--sep--World!-- ``` ### input() Python內建的輸入函式 在input()括號內可以填入字串 input()被呼叫時會輸出括號內的字串 **Note :** 通常會宣告變數來儲存input()內容 **Note :** input() 的 return dataType 預設為string ``` x = input("Please input->") print(x * 2) Input : 1 Output : Please input-> 11 # Since input datatype is string , so '1'*2 = '11' ``` #### 將input()的dataType轉為int ``` # 將input()放在int()的括號裡 # Note : int() is a function which can change dataType x = int(input()) print(x * 2) Input : 1 Output : 2 # int('1') = 1 , 1 * 2 = 2 ``` 在這個例子裡,如果輸入的data無法轉換為int時就會引發**Error** ex: 如果Input data改為 a 程式就無法正常進行 : ValueError: invalid literal for int() with base 10: 'a' #### 將input()的dataType轉為float ``` # 將input()放在float()的括號裡 # Note : float() is a function which can change dataType x = float(input()) print(x * 2) Input : 1.0 Output : 2.0 # float('1.0') = 1.0 , 1.0 * 2 = 2.0 ``` 在這個例子裡,如果輸入的data無法轉換為float時就會引發**Error** ex: 如果Input data改為 a 程式就無法正常進行 : ValueError: invalid literal for float() with base 10: 'a' ### 其他 build-in functions: #### int() 將傳入的資料的dataType轉為int return type : int 用法: ``` x = "123" y = int(x) print(type(x),type(y)) Output : <class 'str'> <class 'int'> ``` #### float() 將傳入的資料的dataType轉為float return type : float 用法: ``` x = "123.456" y = float(x) print(type(x),type(y)) Output : <class 'str'> <class 'float'> ``` #### str() 將傳入的資料的dataType轉為string return type : string 用法: ``` x = 123 y = str(x) print(type(x),type(y)) Output : <class 'int'> <class 'str'> ``` #### type() 回傳 "傳入的資料的dataType" return type : type 用法: ``` x = 123 print(type(x)) Output : <class 'int'> ``` #### ord() & chr() **ord() :** return type : int 用法: ``` x = "A" y = ord(x) print(y,type(y)) Output : 65 <class 'int'> ``` **chr() :** return type : string 用法: ``` x = 65 y = chr(x) print(y,type(y)) Output : A <class 'str'> ``` > ord(chr(x)) = x > chr(ord(y)) = y > chr() & ord() function use ASCII table 來對照數字與字元 #### max() return Type : int , string return int 用法: ``` print(max(1,2,3,4,5,6,7,8)) Output: 8 # 如果只傳入一個整數 -> TypeError # TypeError: 'int' object is not iterable ``` ``` # 上面例子的第二種寫法 list = [i+1 for i in range(8)] print(max(list)) ``` **Note :** list將會在之後的筆記教學 return string 用法: ``` print(max("abc")) print(max("abc","cba")) Output: c cba # c > b > a in ASCII table # 比較字串時會從第一個字元開始比,相同則比較下一個字元 # 相同到最後時回傳較長字串 ``` #### min() return Type : int or string 用法:同 max() ### 自訂function **Note :** Python很注重對齊,def的下一行要加一個Tab來表示def尚未結束 若下一行開頭沒有Tab,就代表def定義的結束 語法: ``` def functionName(參數1,參數2): pass # pass通常在function還未寫入任何程式碼時使用 # 如果function內沒有程式碼時被呼叫 -> Error # IndentationError: expected an indented block after function definition # 可以不傳入任何參數 # function name 不可設為 Keyword ``` 例子1: ``` def plus(a , b): c = a + b return c x = "abc" y = "def" z = plus(x,y) print(z) Output : abcdef ``` 例子2: ``` def Print_plus(a , b): c = a + b print(c) x = "abc" y = "def" z = Print_plus(x,y) Output : abcdef ``` #### lambda (anonymous function) lambda 也是 function 的一種 語法: ``` lambda parameters: expression ``` 例子: ``` two = lambda: 2 sqr = lambda x: x * x pwr = lambda x, y: x ** y T = two() S = sqr(2) P = pwr(2,3) print(T,S,P) Output : 2 4 8 ``` ## 基本 Operator 介紹 (加減乘除) ### + 分為binary,unary兩種 #### binary : 範例用法: ``` a = 1 b = 2 c = a + b print(a,b,c) Output : 1 2 3 ``` #### unary : 範例用法: ``` a = -1 b = +a print(a,b) Output : -1 -1 ``` ### - 分為binary,unary兩種 #### binary : 範例用法: ``` a = 1 b = 2 c = a - b print(a,b,c) Output : 1 2 -1 ``` #### unary : 範例用法: ``` a = 1 b = -a print(a,b) Output : 1 -1 ``` ### * '*'在Python裡是乘號 範例用法: ``` a = 1 b = 2 c = a * b print(a,b,c) Output : 1 2 2 ``` ### / '/' 在Python裡是除號 範例用法: ``` a = 2 b = 1 c = a / b print(a,b,c) Output : 1 2 2.0 ``` **Note :** 只要經過除法運算,就算沒有餘數,dataType也會轉換成float ### ** 在Python中兩個乘號是次方的意思 範例用法: ``` a = 2 b = 10 c = a**b print(a,b,c) Output : 2 10 1024 ``` ### // 在Python中兩個除號是整除的意思 會無條件捨去小數部分 範例用法: ``` a = 2 ; b = 10 c = b//a d = 3 ; e = 2 f = d//e print(c,f) Output : 5 1 ``` **Note:** 若要在一行內宣告不同的變數並賦值,則需要用分號(;)隔開 ### % 在Python中%是取餘數的意思 範例用法: ``` a = 10 b = 3 c = a%b print(a,b,c) Output : 10 3 1 ``` ### 比較operator * a==b :判斷左右變數是否**相等** * a!=b :判斷左右變數是否**不相等** * a\>b :判斷左變數是否**大於**右變數 * a<b :判斷左變數是否**小於**右變數 * a\>=b : 判斷左變數是否**大於等於**右變數 * a<=b : 判斷左變數是否**小於等於**於右變數 ## if-else 用法 語法: ``` if 條件 : 內容 內容 當條件為True時,內容才會被執行 ``` **Note:** Python很注重對齊,if的下一行要加一個Tab來表示if尚未結束 若下一行開頭沒有Tab,就代表if的結束 範例用法: ``` a = 1 b = 2 if a>b : print("a>b") Output: # 沒有輸出,因為a<b ``` **加入else:** 語法: ``` if 條件 : 內容 內容 else: 內容 ``` 範例用法: ```python a = 1 b = 2 if a>b : print("a>b") else: print("a<b") # Output: # a<b ``` **加入elif:** 語法: ``` if 條件1 : 內容 內容 elif 條件2: 內容 elif 條件3: 內容 ``` 範例用法: ``` a = 1 b = 2 if a>b : print("a>b") elif a>0 : print("a>0") elif(a<b): print("a<b") Output: a>0 ``` **同時使用elif else:** 語法: ``` if 條件1 : 內容 內容 elif 條件2: 內容 elif 條件3: 內容 else: 內容 ``` 範例用法: ``` a = 1 b = 2 if a>b : print("a>b") elif a>0 : print("a>0") elif(a<b): print("a<b") else: print("else") Output: a>0 ``` **Note:** Python會按照順序往下執行,只要上面的elif被執行,下面的elif與else就都不會進行判斷 ### and , or , not **Note:** and , or , not 都是Keyword 優先順序:not -> and -> or(越前面代表越先判斷) 用法:在一個if內同時判斷多個條件 範例: ``` a = 1 b = 2 c = 3 if not a>b and not b>c or c>a and c>b: print("it's true") Output : it's true ``` ``` 解析: not a>b and not b>c or c>a and c>b a>b -> False b>c -> False c>a -> True c>b -> True not 優先處理: not a>b -> True not b>c -> True and 第二處理: True and True -> True # (not a>b) and (not b>c) True and True -> True # (c>a) and (c>b) or 最後處理: True or True -> True # ((not a>b) and (not b>c)) or ((c>a) and (c>b)) ``` | A | B | A and B | |:-----:|:-----:|:-------:| | True | True | True | | True | False | False | | False | True | False | | False | False | False | | A | B | A or B | |:-----:|:-----:|:------:| | True | True | True | | True | False | True | | False | True | True | | False | False | False | | A | not A | |:-----:|:-----:| | True | False | | False | True | ### & , | , ~ & , | , ~ 在Python是用來做位元運算的工具 用法:將int轉為二進位進行運算 ``` a = 100 # 100 = 64 + 32 + 4 # 0b01100100 = 100 b = 148 # 148 = 128 + 16 + 4 # 0b10010100 = 148 c = a & b d = a | b e = ~a f = ~b print(c,d,e,f) Output : 4 244 -101 -149 ``` ``` 對每位進行 & 運算: 01100100 10010100 -> 00000100 對每位進行 | 運算: 01100100 10010100 -> 11110100 ``` **Note:** ~num = -(num+1) | A | B | A & B | |:---:|:---:|:-----:| | 1 | 1 | 1 | | 1 | 0 | 0 | | 0 | 1 | 0 | | 0 | 0 | 0 | | A | B | A \| B | |:---:|:---:|:------:| | 1 | 1 | 1 | | 1 | 0 | 1 | | 0 | 1 | 1 | | 0 | 0 | 1 | ### ^ (xor operator) ``` a = 1 b = 0 print(a^a,end=" , ") print(b^b,end=" , ") print(a^b,end=" , ") print(b^a,end=" ") Output : 0 , 0 , 1 , 1 ``` **只要 a 與 b 相同, a^b 就會為 0** | A | B | A ^ B | |:---:|:---:|:-----:| | 1 | 1 | 0 | | 1 | 0 | 1 | | 0 | 1 | 1 | | 0 | 0 | 0 | ## 迴圈(for , while) ### for 語法: ``` for 變數 條件 : 內容 ``` 用法範例: ``` for i in range(10): print(i , end = " ") Output: 0 1 2 3 4 5 6 7 8 9 ``` 在範例中, i 是宣告的變數名稱,當我們在 for loop 後面加上 print(i) 後,會輸出 9 **Note :** in 跟 range 都是 python 中常見的 keyword ,要知道用法 ### range | range(n) | 從整數 0 到 n-1 | |:----------------:|:--------------------------:| | range(n , m) | 從整數 n 到 m-1 | | range(n , m , s) | 從整數 n 到 m-1 ,間隔為 s | 用法範例: ``` for i in range(1,10,2): print(i , end = " ") Output: 1 3 5 7 9 ``` ### while 語法: ``` while 條件 : 內容 ``` 用法範例: ``` i = 0 while i in range(10): print(i , end = " ") i += 1 Output: 0 1 2 3 4 5 6 7 8 9 ``` 範例 2 : ``` i = 0 while True : if i > 9 : break print(i , end = " ") i += 1 ``` 如果不事先宣告 i 的話 , python 會因為找不到 i 而引發 NameError ,因此使用 while 前需要多加注意;另外還有第二個要注意的點就是要避免 while 進入到無窮迴圈 無窮迴圈範例: ``` i = 0 while i in range(10): print(i , end = " ") # i += 1 ``` 因為 while 會執行到條件錯誤為止,所以當我們將 i+=1 註解時, i 就會永遠是 0 ,這時候程式碼就會進入到一個無窮迴圈 ### else 搭配 loop 跟在 loop 後的 else 會在迴圈**正常**結束時執行 但如果迴圈中有 **break** 執行,那麼 else 內的程式碼將不會被執行 範例: ``` i = 0 while i < 4 : i += 1 print(i) else : print("end") Output : 1 2 3 4 end ``` 範例: ``` i = 0 while True : if(i > 4) : break i += 1 print(i) else : print("end") Output : 1 2 3 4 5 ``` ## 基礎資料結構介紹 List , Tuple , Dictionary , Set 是 python 中常用的資料結構,下面會一一介紹 ### List **初始化**: ``` # list 名稱可以自訂 list = [] temp = [1 , 2] ``` > **list index** 算法: list [0] , list [1] , list [2] , list [3] ... > 最後一個 index 值為 -1 ,以此類推倒數第 n 個 index 就是 -n **list 基礎操作**: ``` print(list) # 印出list內所有元素 print(temp[0]) # 印出temp的第一個元素 l = len(list) # list 內元素個數 del temp[1] # 刪除第二個元素 temp.append(3) # 在 temp 的末端加入 3 temp.insert(1 , 7) # 在第 2 (1+1) 個位置插入 7 print(temp.count(1)) # 輸出temp內有幾個 1 temp.sort() # 按照大小排序 m = max(temp) # temp 中最大值 n = min(temp) # temp 中最小值 ``` List 還有很多內建 function 可以在 Python 的 function 庫中查詢 > **Note :** List 內的資料型態不一定是相同的 > 當資料型態不同時,使用 sort function 時要注意 TypeError print list 用法範例: ``` list = [1 , "LIST" , 20.87 , True] print(list) # 法一 print('[' , end = "") # 法二 for ele in list: print(ele , end = " ") print(']') print('[' , end = "") # 法三 for i in range(len(list)): print(list[i] , end = " ") print(']') Output: [1, 'LIST', 20.87, True] [1 LIST 20.87 True ] [1 LIST 20.87 True ] ``` 將其他資料型態轉為 list : ``` list(tuple) -> change data type from tuple to list list(string) -> [s[0], s[1], s[2], ... , s[len(string)] ] list(range) -> [front , ... , end] ``` 用法範例: ``` str = "input" # str = input() ran = range(1,16,2) print(list(str)) print(list(ran)) Output: ['i', 'n', 'p', 'u', 't'] [1, 3, 5, 7, 9, 11, 13, 15] ``` ### Tuple tuple 是一種跟 list 類似卻不能直接修改元素的一種資料型態 **初始化**: ``` # tuple 名稱可以自訂 tuple1 = () tuple2 = (1 ,) tuple3 = 1., tuple4 = (1, 2, 3 ,4) tuple5 = 1, 2 ,3 ,4 list = [tuple1,tuple2,tuple3,tuple4,tuple5] for ele in list : print(ele) Output : () (1,) (1.0,) (1, 2, 3, 4) (1, 2, 3, 4) ``` > **Note :** 初始一個元素的 tuple 的語法需要加上 ' **,** ' > 以 tuple3 為例,如果沒有加 , 1.0 會變成 float 的資料型態,而不是 tuple **tuple 基礎操作**: ``` print(tuple5) # 印出list內所有元素 print(tuple5[0]) # 印出temp的第一個元素 l = len(tuple) # list 內元素個數 print(tuple5.count(1)) # 輸出tuple5內有幾個 1 ``` > 因為 tuple 沒有 append() function 跟 del , 但是可以用 use "tuple + (1, 10)" 或 "tuple * 2",也可以將 tuple 轉為 list 後更改元素再轉換回來 其餘用法都與 list 相似 將其他資料型態轉為 tuple : ``` tuple(list) -> change data type from list to tuple tuple(string) -> (s[0], s[1], s[2], ... , s[len(string)]) tuple(range) -> (front , ... , end) ``` ### dict ( Dictionary ) **初始化**: ``` # dict 名稱可以自訂 dict1 = {} dict2 = {"cat": "chat", "dog": "chien"} dict3((1,2),(3,4)) # dict3 = {1:2, 3:4} # {key : value} ``` > 在 print dictionary 時輸出順序可能會改變,這是因為 dict 會自動排序元素 **dict 基礎操作**: ``` print(dict.keys()) # 已自動排序 print(dict.values()) for i, j in dictionary.items() : # i : key , j : value print(i , " : " , j) adding new item in dictionary : # 法一 : dictionary.update({key : value}) # 法二 : dictionart[key] = value removing key : # 法一 : del dictionary[key] # 法二 : dictionary.popitem() # Notice: In Python version before 3.6.7 ,popitem() will randomly pop item dictionary.clear() : clear all items in dictionary dic2 = dic1.copy() : copy items in dic1 (dic2 is dic1 == False) ``` ### Set **初始化**: ``` set1 = set() set2 = {1 , 2 , 3} ``` > **Note :** 空 set 的宣告要用 set() **set 基礎操作**: ``` TODO ``` ## Error Type 列出 error 列表程式碼: ``` def print_exception_tree(thisclass, nest = 0): if nest > 1: print(" |" * (nest - 1), end="") if nest > 0: print(" +---", end="") print(thisclass.__name__) for subclass in thisclass.__subclasses__(): print_exception_tree(subclass, nest + 1) print_exception_tree(BaseException) ``` ### try & except 配合上面提到的 error type 來進行操作 try : 想執行的程式碼 except : 發生錯誤時會執行的程式碼(可指定錯誤) 範例: ``` TODO ``` 也可以搭配 else , finally 做使用 else : 若 except 未執行,try 結束後便會執行 finally : 不管有沒有錯誤都會執行 範例: ``` TODO ``` <!-- <style> html, body, .ui-content { background-color: #333; color: #ddd; } body > .ui-infobar { display: none; } .ui-view-area > .ui-infobar { display: block; } .markdown-body h1, .markdown-body h2, .markdown-body h3, .markdown-body h4, .markdown-body h5, .markdown-body h6 { color: #ddd; } .markdown-body h1, .markdown-body h2 { border-bottom-color: #ffffff69; } .markdown-body h1 .octicon-link, .markdown-body h2 .octicon-link, .markdown-body h3 .octicon-link, .markdown-body h4 .octicon-link, .markdown-body h5 .octicon-link, .markdown-body h6 .octicon-link { color: #fff; } .markdown-body img { background-color: transparent; } .ui-toc-dropdown .nav>.active:focus>a, .ui-toc-dropdown .nav>.active:hover>a, .ui-toc-dropdown .nav>.active>a { color: white; border-left: 2px solid white; } .expand-toggle:hover, .expand-toggle:focus, .back-to-top:hover, .back-to-top:focus, .go-to-bottom:hover, .go-to-bottom:focus { color: white; } .ui-toc-dropdown { background-color: #333; } .ui-toc-label.btn { background-color: #191919; color: white; } .ui-toc-dropdown .nav>li>a:focus, .ui-toc-dropdown .nav>li>a:hover { color: white; border-left: 1px solid white; } .markdown-body blockquote { color: #bcbcbc; } .markdown-body table tr { background-color: #5f5f5f; } .markdown-body table tr:nth-child(2n) { background-color: #4f4f4f; } .markdown-body code, .markdown-body tt { color: #eee; background-color: rgba(230, 230, 230, 0.36); } a, .open-files-container li.selected a { color: #5EB7E0; } </style> -->