AndyChiang
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    1
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Python 基礎技術整理 [![](https://img.shields.io/badge/dynamic/json?color=orange&label=總觀看人數&query=%24.viewcount&url=https://hackmd.io/3L8iXhnVR2uFC_4iJs-n3g%2Finfo)]() > [name=AndyChiang][time=Fri, Jan 29, 2021 4:19 PM][color=#00CDAF] ###### tags: `Python` ## 安裝 [使用 Visual Studio Code 設定您的 Python 初學者開發環境](https://docs.microsoft.com/zh-tw/learn/modules/python-install-vscode/) 在Window的命令提示字元(CMD)輸入以下指令: ``` $ py -- version ``` 如果回應是這個,代表已經安裝成功,沒有的話就去安裝吧。 ``` Python 3.X.X ``` [Python 載點](https://www.python.org/downloads/) ## Python 互動模式 ### 啟動 Python 的互動模式 在CMD輸入: ``` $ py -3 ``` 會得到: ``` >>> ``` 然後就可以在 `>>>` 之後接上程式碼,電腦將一行行執行。 ### 離開互動模式 在 `>>>` 之後輸入: ``` exit() ``` ## Python 註解(comments) ### 單行註解 ``` # 註解寫在這行 ``` ### 多行註解 ``` """ 第一行註解 第二行註解 """ ``` Python內建沒有提供多行註解,但因為編譯器會自動忽略未定義變數的字串,所以這樣也行。 ## Python 變數(variables) ### 基本型態 Python不像C或Java,不需要宣告型態,而是在初次賦予值時決定,通常有這幾種型態: * int:整數 * float:浮點數(小數) * complex:虛數,虛部以 j 表示 * str:字串,用單引號或雙引號都一樣 * list:列表,以 `[ ]` 包覆 * tuple:組合,以 `( )` 包覆 * range:範圍,形式為 `range(數字)` * set:集合,以 `{ }` 包覆 * dict:字典,JSON格式 `{ "A" : a, "B" : b }` * bool:布林值,有True和False ### 型態轉換(Casting) * int():將內容轉為整數 * float():將內容轉為浮點數 * str():將內容轉為字串 ### 取得型態 * type():取得內容的型態 ### 變數命名 基本上和C是一樣的,且有分大小寫。 ### 賦予值 #### 多個變數賦予多個值 ``` x, y, z = "Orange", "Banana", "Cherry" ``` #### 多個變數賦予單個值 ``` x = y = z = "Orange" ``` #### 拆包(Unpacking) 當賦予值是清單時,Python允許使用拆包。 ``` fruits = ["apple", "banana", "cherry"] x, y, z = fruits ``` ``` # x = apple # y = banana # z = cherry ``` ### 全域變數 如果在函式內宣告變數的話,該變數為局部變數。但如果想要在函式內宣告全域變數的話,請在變數前加上 `global` 。 ### 隨機數 ``` import random print(random.randrange(1, 10)) ``` 基礎函式庫沒有,所以要另外引入。 ## Python 字串(strings) 和C一樣,字串就是一個字元的陣列,以下為字串的函式: ### 字串長度 ``` str = "Hello, World!" print(len(str)) #13 ``` 使用 `len(字串)` 可以取得字串長度。 ### 搜尋單字 ``` str = "The best things in life are free!" print("free" in str) #True ``` 使用 `字串A in 字串B` ,如果有就回傳**True**,反之回傳**False**。 ### 切割字串 ``` str[2:5] ``` 切割str從第二位到第四位的部分。 ### 轉大寫 ``` str.upper() ``` ### 轉小寫 ``` str.lower() ``` ### 刪除多餘空格 刪除字串前後多餘的空格。 ``` str.strip() ``` ### 替換字串 將字串內一個單字替換成另一個單字。 `replace()` 並不會改變原字串。 ``` a = a.replace("H", "J") ``` ### 分割字串 以某個單字做分割,回傳值為一個字串的list。 ``` str.split(",") ``` ### 格式化字串 使用 `.format(內容)` 將內容置入字串中 `{}` 的位置,預設會依照順序排,如果要指定的話,則可以寫:`{數字}`。 ``` age = 36 str = "I am {}" print(str.format(age)) ``` ``` quantity = 3 itemno = 567 price = 49.95 myorder = "I want to pay {2} dollars for {0} pieces of item {1}." print(myorder.format(quantity, itemno, price)) ``` #### 格式化字符 * `{:數字}`,預留N個空格,類似C語言中的 `%Nd` * `{:.2f}`,小數點下N位 * [更多...](https://www.w3schools.com/python/ref_string_format.asp) #### 210208更新 - New way! 如果在字串前加上英文字母 `f` 或 `F`,字串會轉成格式化字串,直接在字串內的 {} 中加入變數即可。 ``` name = "Andy" pro = "student" string = f"My name is {name}, and I am a {pro}" ``` * 參考網址:[Python 3's f-Strings: An Improved String Formatting Syntax (Guide)](https://realpython.com/python-f-strings/#f-strings-a-new-and-improved-way-to-format-strings-in-python) #### 210729更新 - 正規表達式 字串前加上 `r` 表示正規表達式,像 `r"[0-9]"`。 ### 跳脫字元 常見的跳脫字元有: * `\`:區分關鍵字和字串 * `\n`:換行 ## Python 運算子(operators) 基本上和C差不多,我只講幾個較特別的。 ### 算術運算符 * `**`:指數(次方) ### 邏輯運算符 * `and`:且,等於`&&` * `or`:或,等於`||` * `not`:非,等於`!` ### 身份運算符 * `is`:跟`==`的差別在於,不只內容一樣,更要是相同的物件 * `is not`:`is`的相反 ### 會員運算符 * `in`:檢查A有沒有在B之中 * `not in`:`in`的相反 ## Python 容器(Collections) Python提供了四種容器,分別為: * 列表(list):有序且可更改的容器,允許重複的成員。 * 組合(tuple):是有序且不可更改的容器,允許重複的成員。 * 集合(set):是無序和未索引的容器,沒有重複的成員。 * 字典(dict):是無序且可變的容器,沒有重複的成員。 ### 列表(list) ``` list = ["a","b","c"] ``` #### 轉成列表 ``` list(("a","b","c")) #注意要雙括號 ``` #### 切割列表 **別忘了列表陣列第一個的索引值是 0 喔!** 從第二個切到第三個(不包括第四個)。 ``` thislist = ["a", "b", "c", "d", "e"] print(thislist[1:3]) # ["b", "c"] ``` 從第三個切到列表底。 ``` thislist = ["a", "b", "c", "d", "e"] print(thislist[2:]) # ["c", "d", "e"] ``` 從列表頭切到第四個(不包括第五個)。 ``` thislist = ["a", "b", "c", "d", "e"] print(thislist[:4]) # ["a", "b", "c", "d"] ``` 從第一個切到第四個(不包括第五個),每兩個取一個。 ``` thislist = ["a", "b", "c", "d", "e"] print(thislist[0:4:2]) # ["a", "c"] ``` 另外,負索引則代表從列表底倒數第幾個。 從列表頭切到倒數第三個("c"),但不包刮 "c",所以切到 "b"。 ``` thislist = ["a", "b", "c", "d", "e"] print(thislist[:-3]) # ["a", "b"] ``` 此小技巧將**列表反轉**。 ``` thislist = ["a", "b", "c", "d", "e"] print(thislist[::-1]) # ['e', 'd', 'c', 'b', 'a'] ``` #### 追加項目 使用 `.append()` 將項目加在陣列末端。 #### 插入項目 使用 `.insert()` 會在其index的前面插入新的值,並把原先的值往後移動一格。 ``` thislist = ["apple", "banana", "cherry"] thislist.insert(1, "orange") # thislist = ['apple', 'orange', 'banana', 'cherry'] ``` #### 擴展列表 使用 `extend()` ,將其他任意陣列類型接在當前列表末端。 ``` thislist = ["apple", "banana", "cherry"] tropical = ["mango", "pineapple", "papaya"] thislist.extend(tropical) # thislist = ['apple', 'banana', 'cherry', 'mango', 'pineapple', 'papaya'] ``` #### 刪除指定項目 ``` list.remove("banana") ``` #### 刪除指定索引 ``` list.pop(1) ``` 未指定數字則刪除最後一位。 #### 刪除(del) 刪除指定索引: ``` del list[0] ``` 刪除整個陣列: ``` del list ``` #### 清空列表 ``` list.clear() ``` 陣列還存在,只是內容清空。 #### 列表理解(List Comprehension) 比如說我今天想要篩選出 `fruit` 列表中包含 `a` 的項目,我可能會這樣寫: ``` fruits = ["apple", "banana", "cherry", "kiwi", "mango"] newlist = [] for x in fruits: if "a" in x: newlist.append(x) print(newlist) ``` 其實可以簡化成一行: ``` fruits = ["apple", "banana", "cherry", "kiwi", "mango"] newlist = [x for x in fruits if "a" in x] print(newlist) ``` ##### 語法 ``` newlist = [expression for item in iterable if condition == True] ``` * newlist:新列表 * expression:新列表的項目 * item:原列表的項目 * iterable:原列表 * condition:條件式,True就會加入新列表 #### 排序列表 ``` list.sort() ``` 英文的話會照英文字母排,數字則是從小排到大。 ##### 降冪排序 ``` list.sort(reverse = True) ``` ##### 自訂排序 ``` list.sort(key = myfunc) ``` myfuc可以是任何自訂的函式。 #### 反轉列表 ``` list.reverse() ``` #### 複製列表 ``` newlist = thislist.copy() ``` #### 計算指定值的個數 ``` x = thislist.count("apple") ``` ### 組合(tuple) ``` tuple = ("a","b","c") ``` 基本上跟列表的函式一樣,差別在於組合不可更改成員,因此想要新增或刪除成員時,解決方法是將組合轉為列表 `list()` ,更改內容,然後再轉回組合。 ``` thistuple = ("apple", "banana", "cherry") y = list(thistuple) y.append("orange") thistuple = tuple(y) ``` #### 轉成組合 ``` tuple(("a","b","c")) #注意要雙括號 ``` ### 集合(set) ``` set = {"a","b","c"} ``` #### 轉成集合 ``` set(("a","b","c")) #注意要雙括號 ``` #### 新增單一值到集合中 ``` thisset.add("orange") ``` #### 新增其他陣列到集合中 ``` set1.update(set2) ``` ``` set3 = set1.union(set2) ``` union也行,只是會返回新集合。 #### 刪除指定項目 ``` thisset.remove("banana") ``` ``` thisset.discard("banana") ``` 一樣是刪除,但 `remove()` 如果刪除項目不存在將會引發錯誤, `discard()` 則不會。 ``` x = thisset.pop() ``` pop() 則是刪除並傳回最後一位的值,但記得集合是無序的嗎? 因此沒辦法知道會刪掉什麼。 #### 兩集合交集(AND) ``` z = x.intersection(y) ``` #### 兩集合互斥或(XOR) ``` z = x.symmetric_difference(y) ``` ### 字典(dict) ``` dict = {"a" : A, "b" : B, "c" : C} ``` 基本形式為 `key : value` #### 訪問項目 ``` x = thisdict["key"] ``` ``` x = thisdict.get("key") ``` 兩種都是獲取key相對的value。 #### 取得key ``` x = thisdict.keys() ``` 回傳值為字典中所有key的列表(list)。 #### 取得value ``` x = thisdict.values() ``` 回傳值為字典中所有value的列表(list)。 #### 取得項目 ``` x = thisdict.items() ``` 回傳值為字典中所有項目的列表(list),項目以組合(tuple)型態回傳,如`(key, value)`。 #### 變更/新增項目 ``` thisdict["color"] = "red" ``` ``` thisdict.update({"color": "red"}) ``` 如果不存在此key,則為新增項目。 #### 刪除項目 ``` thisdict.pop("key") ``` 刪除指定key的項目。 #### 複製項目 ``` dict2 = ditc1.copy() ``` `dict2 = ditc1` 是無效的,必須使用 `copy()`。 #### 巢狀字典 簡單講,就是字典內再包一個字典。 ``` myfamily = { "child1" : { "name" : "Emil", "year" : 2004 }, "child2" : { "name" : "Tobias", "year" : 2007 }, "child3" : { "name" : "Linus", "year" : 2011 } } ``` ### 陣列(array) Python並沒有提供原生的陣列,但我們可以用list來實作。 #### 一維陣列 ``` A = [0]*5 ``` 產生一個5列的一維陣列,初始為0。 #### 二維陣列 ``` B = [[0]*5 for i in range(3)] ``` 產生一個3列5行的二維陣列,初始為0。 #### 三維陣列 ``` C = [[[0]*5 for i in range(3)] for j in range(2)] ``` 產生一個2*3*5的三維陣列,初始為0,其他依此類推。 [其他方法:如何在 Python 中建立二維陣列](https://www.delftstack.com/zh-tw/howto/python/how-to-initiate-2-d-array-in-python/) ### 陣列通用函數 #### 是否存在?(any()) 使用 `any()` 函數,參數可以是任意陣列(例如:list、tuple...等等),只要陣列中有任意元素為 True ,則回傳 True ,反之則 False。 如果是空字串會回傳 False。 ``` print(any([2>5, 5>0, 0>2])) # True print(any([])) # False ``` #### 是否全部?(all()) 使用 `all()` 函數,參數可以是任意陣列(例如:list、tuple...等等),必須陣列中所有元素為 True,才回傳 True,反之則 False。 如果是空陣列會回傳 True。 ``` print(all([2>1, 3>2])) # True print(all([])) # True ``` #### 串鏈資料(zip()) 使用 `zip()` 函數,參數為多個任意陣列(例如:list、tuple...等等),類別不同也可以,而此函數可以將這多個陣列相對索引的資料重新打包成組合(tuple),並傳回新的陣列物件。 ``` a = ["a", "b", "c"] b = ("A", "B", "C") c = {"1", "2", "3"} print(zip(a, b, c)) # <zip object at 0x000001C538DEA780> ``` 回傳的是一個物件,所以還要強制轉換成我們想要的型態。 ``` a = ["a", "b", "c"] b = ("A", "B", "C") c = {"1", "2", "3"} print(list(zip(a, b, c))) # [('a', 'A', '1'), ('b', 'B', '2'), ('c', 'C', '3')] ``` 如果把他想成二維陣列,眼尖的人就會發現,其實zip()就是做==轉置矩陣==! 如果陣列長度不一樣,則取最短長度。 ``` a = ["a", "b", "c", "d"] b = ("A", "B", "C", "D") c = ["1", "2", "3"] print(list(zip(a, b, c))) # [('a', 'A', '1'), ('b', 'B', '2'), ('c', 'C', '3')] ``` ##### 小技巧 * **未知參數量** 有時候我們會不清楚參數的數量,這時只要將資料存為一個列表,並在列表名稱前加 `*` 就好了。 * **還原** 只要了解未知參數量的方法,就很容易實作了(長度要一樣)! ``` a = ["a", "b", "c"] b = ("A", "B", "C") c = ["1", "2", "3"] print(list(zip(a, b, c))) # [('a', 'A', '1'), ('b', 'B', '2'), ('c', 'C', '3')] ziped = list(zip(a, b, c)) reziped = list(zip(*ziped)) for x in reziped: print(list(x)) # ['a', 'b', 'c'] # ['A', 'B', 'C'] # ['1', '2', '3'] ``` * 字典key、value互換 ``` D = {'s':"黑桃", 'h':"紅心", 'd':"方塊", 'c':"梅花"} print(dict(zip(D.values(), D.keys()))) # 關鍵在於values放於keys前面 # {'黑桃': 's', '紅心': 'h', '方塊': 'd', '梅花': 'c'} ``` * 二維矩陣 - 向右轉90度、向左轉90度 右轉就是先上下翻轉,再做行列互換。 左轉就是先行列互換,再做上下翻轉。 ``` def rotateRight(arr): A = arr[::-1] # 利用切片上下翻轉 return list(map(list, (zip(*A)))) # 行列互換,再利用map函數將zip內的元組轉列表 def rotateLeft(arr): A = list(map(list, (zip(*arr)))) # 行列互換,再利用map函數將zip內的元組轉列表 return list(A[::-1]) # 利用切片上下翻轉 arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] for x in rotateRight(arr): print(x) # [7, 4, 1] # [8, 5, 2] # [9, 6, 3] for y in rotateLeft(arr): print(y) # [3, 6, 9] # [2, 5, 8] # [1, 4, 7] ``` 參考網址:[【python入門教室】(13) 內建函數any(), all(), zip()介紹](https://ithelp.ithome.com.tw/articles/10230859) ## Python if...else ``` a = 200 b = 33 if b > a: print("b is greater than a") elif a == b: print("a and b are equal") else: print("a is greater than b") ``` Python中的if是靠著縮排來定義區塊的,因此**縮排很重要!!!** 然後Python不管是if或for或function,**都記得加`:`!** * `if condition:`:if * `elif condition:` :else if * `else:` :else ### 簡短if...else ``` print("A") if a > b else print("B") #if成立印出A,否則印出B ``` ### 宣告通過 ``` if a > b: pass ``` 照理來說,如果if後面不做事情的話會報錯。加 `pass` 就沒這個問題了,並不會發生任何事情。 ## Python 迴圈(loops) Python就跟其他程式語言一樣,提供兩種迴圈: ### While 迴圈 ``` i = 1 while i < 6: print(i) i += 1 ``` 只要條件為真,迴圈就會一直執行下去。 ### For 迴圈 ``` fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) ``` 和一般的For迴圈不太一樣,Python的For迴圈比較像是在走訪任意一種陣列(list、tuple...)的每個項目。 #### range()函數 ``` range(5) #表示從0到4的值 range(2, 5) #表示從2到4的值 range(2, 30, 3) #表示2到29的值,每次遞增3 ``` ### 迴圈關鍵字 While 以及 For 迴圈皆可使用 * `break` * `continue` * `else:` :當迴圈結束時執行 ## Python 函數(functions) ### 宣告函數 使用 `def` 來宣告函數。 ``` def my_function(): #TO DO ``` ### 呼叫函數 直接寫名稱就好了,記得加括號。 ``` my_function() ``` ### 參數(args) ``` def my_function(name): print("Hello, " + name) my_function("Andy") ``` ### 任意參數(\*args) 當參數數量不確定時,在參數前加上 `*` ,參數將以組合(tuple)形式傳入函數。 ``` def my_function(*names): print("Hello, " + names[0]) my_function("Andy", "Tobias", "Linus") ``` ### 關鍵字參數(kwargs) 可以指定 key = value,此時的順序不重要。 ``` def my_function(name3, name2, name1): print("Hello, " + name2) my_function(name1 = "Andy", name2 = "Tobias", name3 = "Linus") ``` ### 任意關鍵字參數(\*\*kwargs) 當參數數量不確定時,在參數前加上 `**` ,參數將以字典(dict)形式傳入函數。 ``` def my_function(**names): print("Hello, " + name["name2"]) my_function(name1 = "Tobias", name2 = "Refsnes") ``` ### 傳回值 ``` return value ``` ### Lambda 函數 Lambda是一個簡單的匿名函數,格式為: ``` x = lambda a, b : a * b print(x(5, 6)) #30 ``` 為何要使用Lambda函數? 因為可以讓一個函數重複使用,例如: ``` def myfunc(n): return lambda a : a * n mydoubler = myfunc(2) mytripler = myfunc(3) print(mydoubler(11)) #22 print(mytripler(11)) #33 ``` **當短時間需要多個相似功能的函數時,可選擇使用Lambda函數。** ## Python 類別/物件(class/object) Python 和 Java 一樣是物件導向程式語言(object oriented),支援所謂的類別以及物件,而物件為類別的實作。 ### 建立類別 使用 `class` 關鍵字: ``` class MyClass: x = 5 ``` ### 建立物件 接續上一個,我們現在有了一個名為 MyClass 的類別,實作出名為 p1 的物件: ``` p1 = MyClass() ``` ### 建構函數 使用 `__init__()` 函數,並於宣告時在括號中加入對應的值。 ``` class Person: def __init__(self, name, age): self.name = name self.age = age p1 = Person("John", 36) ``` ### 類別內函數 直接在類別中宣告一個函數就好了。 ``` class Person: def myfunc(self): print("Hello my name is " + self.name) ``` ### 自身參數 等於 Java 的 `this` ,不過 Python 中可以任意命名,只要放在第一個參數即可。 ### 刪除物件屬性 使用 `del`,刪除 p1 的 name 屬性。 ``` del p1.name ``` ### 空物件 使用 `pass` ,物件為空且不會出錯。 ``` class Person: pass ``` ## Python 繼承(inheritance) 類似 Java 繼承的概念,有父類別和子類別之分,子類別會繼承父類別所有的變數以及函數。 ### 建立子類別 ``` class Child(Parent): pass ``` 父類別可以是任意的類別,在建立子類別時將父類作為參數引入。 ### 子類別建構函數 ``` class Child(Parent): def __init__(self, fname, lname): ``` 建立子類別的 `__init__` 函數時,會覆蓋過父類別的 `__init__` 函數,這就是所謂的==override==。 ``` class Child(Parent): def __init__(self, fname, lname): Parent.__init__(self, fname, lname) self.age = 20 ``` 如果想保留父類別的 `__init__` 函數,請另外呼叫父類別的 `__init__` 函數,也可以在底下添加子類別才有的屬性。 也可以使用 `super()` 函數,將取代父類別的名稱。 ## Python 引用(import) Python之所以會好用,import是精隨阿!! ### 模組 就是一般的Python檔案,副檔名為 `.py`。 ``` # mymod.py def show(name) print("Hello, "+name) ``` ### 引用模組 ``` import mymod mymod.show("Andy") ``` 引用名為 `mymod.py` 的檔案,繼承所有的變數及函數。 ### 重新命名模組 ``` import mymod as m m.show("Andy") ``` 覺得模組名稱太長懶得打,可以重新命名。 ### 從模塊導入部分功能 ``` from mymod import show mymod.show("Andy") ``` 有時模組包太大,只想要部分功能時可使用。 ## Python 日期時間(datetime) Python 沒有原生的時間,必須引用名為 `datetime` 的模組。 ### 取得當前時間 ``` import datetime x = datetime.datetime.now() print(x) # 2021-02-01 08:13:59.312312 ``` ### 建立日期物件 ``` x = datetime.datetime(年, 月, 日, 小時, 分鐘, 秒, 毫秒, 時區) ``` 小時、分鐘、秒、毫秒、時區非必填,預設值為0(時區為None) ### 格式化日期 ``` x.strftime("%A") ``` * %a:星期英文簡寫 * %A:星期英文 * %b:月份英文簡寫 * %D:月份英文 * %d:日期 * %m:月份 * %Y:西元年 * 還有很多... ## Python 數學(math) ### 內建函數 #### 最小值 ``` x = min(5, 10, 25) ``` #### 最大值 ``` y = max(5, 10, 25) ``` #### 絕對值 ``` x = abs(-7.25) ``` #### 次方 ``` z = pow(x, y) ``` #### 小數點以下四捨五入 ``` x = round(x) ``` ### 數學模組 ``` import math ``` #### 平方根 ``` x = math.sqrt(64) ``` #### 無條件進位 ``` x = math.ceil(1.4) ``` #### 無條件捨去 ``` y = math.floor(1.4) ``` [更多...](https://www.w3schools.com/python/module_math.asp) ## Python JSON ### 導入JSON模組 ``` import json ``` ### JSON轉Python ``` p = json.loads(j) ``` ### Python轉JSON ``` j = json.dumps(p) ``` #### 縮排 ``` json.dumps(p, indent=4) ``` 以四個空白為一格tab。 #### 排序 ``` json.dumps(p, sort_keys=True) ``` 依照key字首字母,由A排到Z。 ## Python 正規表達式(RegEx) ### 導入re模組 ``` import re ``` ### 元字符 (metacharacter) 元字符為具有特殊意義的符號: * `[ ]`:數組 * `[A-Z]`:A到Z間的任意字母 * `[0-9]`:0到9間的任意數字 * `[aio]`:包含a或i或o * `[^aio]`:包含a或i或o以外的其他字母 * `\`:特殊字符,通常會在字串開頭加 `r` ,以確保字串被辨識為**原始字符串** * `\A`:指定單字在字串的開頭 * `\Z`:指定單字在字串的尾端 * `\b`:指定單字在字串的開頭或尾端 * `\d`:包含數字(0~9) * `\s`:包含空白格(space) * `\w`:包含字(word),字可以是(任意字母、任意數字以及下底線) * `.`:任意字元 * `^`:指定單字在字串的開頭 * `$`:指定單字在字串的尾端 * `*`:指定單字出現一次以上(包含零次) * `+`:指定單字出現一次以上(不包含零次) ### findall()函數 傳回包含所有匹配項的列表,如果沒找到則傳回空列表。 ``` x = re.findall("ai", txt) ``` ### search()函數 傳回第一個找到的匹配項,傳回值為物件,沒找到則傳回 `None`。 ``` x = re.search("\s", txt) print(x.start()) ``` ### split()函數 傳回一個列表,列表中的字串會依照指定字符切割。 ``` x = re.split("\s", txt) ``` ### sub()函數 傳回一個字串,新字串將匹配字符替代成指定字符,類似replace。 ``` x = re.sub("\s", "9", txt) ``` ## Python 報錯機制(try...except...) 和 Java 的 try...catch... ,一樣的原理,學過就簡單。 ### 架構 ``` try: print(x) except: print("Something went wrong") else: print("Nothing went wrong") finally: print("The 'try except' is finished") ``` * try:測試這段程式碼。 * except:如果在try階段出錯,就會直接來執行這段。 * else:如果在try階段沒有出錯,最後會來執行這段。 * finally:無論有無出錯,最後一定會執行這段。 ### 拋出異常(raise an exception) 如同Java的throw: ``` if x < 0: raise Exception("Sorry, no numbers below zero") ``` ## Python 輸入/輸出(I/O) ### 使用者輸入 input()函數回傳使用者在屏幕上輸入的值,`()`內的字則印在輸入之前: ``` username = input("Enter username:") print("Username is: " + username) ``` ### 輸出 最簡單就是用 `print()` 函數,印出結果在屏幕上,會自動換行: ``` print("Hello, World!") ``` ## Python 檔案(file) ### 開啟檔案 ``` f = open("demo.txt","r") ``` 開啟檔案需要兩個參數,檔案路徑和開啟模式。 #### 檔案路徑 * 絕對路徑 * 相對路徑 #### 開啟模式 * "r":讀取(預設值),讀取文件內容,如果檔案不存在則返回錯誤。 * "a":追加,追加內容在文件後面,如果不存在則創建文件。 * "w":寫入,會覆蓋掉原先文件的內容,如果不存在則創建文件。 * "x":創建,創建指定的文件,如果文件存在則返回錯誤。 另外可以選讀取模式 * "t",文本(默認值),文字模式 * "b",二進制,二進制模式(例如圖像) ### 讀取檔案 ``` f = open("demo.txt", "r") print(f.read()) ``` 可以指定讀取的字元數: ``` print(f.read(5)) # 只讀前五個字元 ``` 也可以一次讀一行: ``` print(f.readline()) ``` ### 寫入檔案 ``` f = open("demo.txt", "a") f.write("New content!") ``` ``` f = open("demo.txt", "w") f.write("New content!") ``` ### 創建檔案 ``` f = open("demo.txt", "w") ``` ### 刪除檔案 **必須引用 os 模組!** ``` import os os.remove("demo.txt") ``` ### 檢查檔案是否存在 如果檔案不存在會報錯,所以建議在刪除檔案前檢查一遍,其他創建、寫入檔案也是一樣的道理。 ``` import os if os.path.exists("demo.txt"): os.remove("demo.txt") else: print("The file does not exist") ``` ### 新增資料夾 ``` import os os.mkdir("folder1") ``` ### 刪除資料夾 ``` import os os.rmdir("folder1") ``` ### CMD操作 ``` os.system("CMD 指令") ``` 更多:[python 讀寫、建立檔案的方法](https://codertw.com/%E7%A8%8B%E5%BC%8F%E8%AA%9E%E8%A8%80/368002/) ### with...as...(建議寫法) 上面開關檔的方法當然也可以,但檔案處理過程中若是出了什麼意外,程式會直接中斷,造成已開啟的檔案未正常關檔,這時可以使用Python的with...as...寫法: ``` with open('demo.txt', 'w') as file: file.write('Hello, world!') ``` 優點為 file 只會在區塊內生效,跳出區塊便會自動關檔,非常方便! 也可以自己客製化資源管理器,但這裡不多說,有需要可以去以下連結看。 參考網址:[Python 的 with 語法使用教學:Context Manager 資源管理器](https://blog.gtwang.org/programming/python-with-context-manager-tutorial/) ## Python 查詢詳細資料 有三個步驟: 1. `type()`:了解它的型態 2. `dir()`:了解它有哪些變數、函數可以使用 3. `help()`:查詢變數、函數的功能 ### Python Help Python內建`help()`,顯示函數的功能簡介。 ``` help(print) >> print(...) print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. flush: whether to forcibly flush the stream. ``` 也可以在自訂函數前,加上簡介,使用`"""`包圍起來。 ``` def function(a, b): """ Sum a and b and return """ return a+b help(function) >> function(a, b) Sum a and b and return ``` ## Python 小抄(好東西) ![](https://i.imgur.com/AIwaQhN.png) ## 相關文章 [Python 進階技術整理](/Q9gE7WIhSVCzvjCbqerCgg) ## 參考網站 * [W3School Python教學](https://www.w3schools.com/python/default.asp) * [Python 官方document](https://docs.python.org/zh-tw/3/tutorial/index.html)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully