--- title: Python 基礎課程 tags: Python, Basic, Lesson description: --- # Python 基礎課程 ## 大綱 [TOC] ## What is Python? * 高階程式語言 * 直譯式語言 > 直譯式 vs 編譯式語言:https://reurl.cc/m9xYXY * 物件導向(object oriented) > 基本上目前不會遇到,遇到(大概)就會知道了 ### 運作原理 * python原始碼 > python直譯器 > 機器碼 > 更詳細:https://reurl.cc/q8G2Qy ### 特色 * 語法簡潔易讀、動態型別 * C++ ```c= #include <iostream> using namespace std; int main() { cout << "Hello! World!"; return 0; } ``` * Java ```Java= public class HelloWorld { public static void main(String[] args) { System.out.println("Hello! World!"); } } ``` * Python ```python= print('Hello World') ``` * 內建標準函式庫 & 第三方函式庫 * 開放原始碼、活耀的社群、完整的線上文件 :::warning 缺點:速度較慢,如果講求極致的速度就不適合用python ::: ### 用途 * 爬蟲:自動化抓取網路資料 * 聊天機器人:Line Bot * 物聯網 * 數據分析 * 網站開發:Django、Flask等後端框架 * 遊戲製作 * … ### 環境設定 ( 安裝Python ) 1. 上官網下載與電腦系統相符合的版本 > 找官網嗎? [點這裡](https://www.python.org/downloads/) 2. 安裝:記得將設為環境變數選項打勾 ![](https://i.imgur.com/Zy3U2UF.png) 3. 設定環境變數 ( 忘記勾環境變數時 ) > Path變數的功能在於,使用cmd輸入指令時,系統會在Path裡面的路徑找你想要執行的程式 (1) 複製 Python 安裝路徑 ( Example: C:\Program Files(x86)\Python36-32 ) (2) 本機 → 點右鍵 → 內容 → 進階系統設定 → 環境變數 (3) 系統變數裡面找到 path 變數 → 按編輯 → 新增 (4) 將剛剛複製的路徑加入 → 按下確定 (5) 確認加入成功 → 打開 CMD 輸入 python ( 看到以下畫面就成功了 ) ![](https://i.imgur.com/ghaV9ur.png) ### 開發工具 * 文字編輯器: 功能較為單純,可透過插件擴充功能 * Notepad++ * Sublime * VSCode * IDE: 包含開發所需工具,功能齊全 * PyCharm * Spyder * Jupyter Notebook :::warning 新手誤區: IDE/文字編輯器 “不等於” python直譯器 可用IDE/文字編輯器執行python是因為它們幫你呼叫python直譯器來執行你的程式碼 ::: ### Python 起手式(以 python IDLE 示範) 1. 創建新檔案:File → New File 2. 打上 (`#`或`##`是註解) ```python= print('Hello World') #print是指把東西印出來 ``` 3. 存檔: * File → Save > 快捷鍵:ctrl + S (Windows)、command + S (Mac) * 檔案結尾加上`.py`或是存檔類型選`Python files` 4. 執行:Run → Run Module ( 看到下面畫面你就成功了 ) > 快捷鍵:F5 ![](https://i.imgur.com/h3fEcG2.png) ## 資料型態 ### 基本概念 #### 物件 ( 像是檔案的內容 ) :::info 在python當中,所有東西都是物件 ::: * 物件的屬性如下: * identity: 物件的記憶體位置,可用`id()`查看 * type: 物件的類型,可用`type()`查看 * value: 物件的值,分為可變 / 不可變 (mutable/immutable) * immutable: * Numeric types: int, float, complex * string * tuple * frozen set * mutable: * list * dict * set * bytearray #### 變數 ( 像是檔案的名稱 ) :::info 在 python 當中,變數可以想像成像是標籤, "指派變數" 則是將各種物件貼上標籤,以方便之後使用 ::: * 使用規則 * 利用 `=` 將物件放進變數裡 :::warning `=` 代表 assign (指派),而不是數學上的等於 ::: * 使用 `A-Z`、`a-z`、`0-9`和 `_` ( 底線 )命名 * Python 會辨別大小寫 * 開頭不能為數字 * 不能使用 Python 的保留字 * 查詢保留字 ```python= import keyword keyword.kwlist # ['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'] ``` * 舉個例子 ```python= pet = "kitty" # 把 "kitty" 這個物件指派給 pet 這個變數 # 換句話說:用 pet 這個變數為 "kitty" 貼上標籤 print(pet) # kitty pet = "puppy" # 一個標籤只能貼在一個物件上,因此 "kitty" 被取代成 "puppy" print(pet) # puppy ``` ### 基本型態 #### 布林值 Boolean (bool) * True * False #### 整數 integer (int) * 以前數學課學到的正整數、負整數、零這些 > 如:1、0、-99 … #### 浮點數 floating-point (float) * 有小數點的數 > 如:0.15、-15.56、77.88 … #### 複數 (complex) * 包含虛數的數字 > 如:1 + 2i、3 + 4i #### 字串 string (str) * 需用單引號 (`''`) 或雙引號 (`""`) 包起來 ( 但前後要相同 ) * 如:"123"、'321'、"abc"、'banana' … #### 運算子 * 算數運算子 > `+`、`-`、`*`、`/`、`//`、`**`、`%` ![](https://i.imgur.com/LfloEef.png) * 賦值運算子 > 算數運算子加一個`=` > ↓↓↓↓↓↓↓ 使用方法以此類推 ↓↓↓↓↓↓↓ ![](https://i.imgur.com/vEMfjfJ.png) * 字串的運算 > 字串也能用`+`及`*` ```python= a = "apple"+"pen" print(a) # "applepen" b = "hello~" * 4 print(b) # "hello~hello~hello~hello~" ``` :::warning 字串相加時兩邊要都是字串型態 不能字串相乘 ( 不信可以試試看 ) ::: ### 容器型態 #### 串列 (list) >以 [value, value, ...] 來"有序"儲存多個值的型式 > ![](https://i.imgur.com/SYMaRBk.png =50%x) ```python= # 創建新list的方式 a = [] b = list() list01 = [1, 3, 5, 7, 9, 11, 13] # 以指定位置找值(第一個值對應index為0,如上圖) print(list01[0]) # 1 print(list01[3]) # 7 #取第一個值到第三個值(注意取頭不取尾) print(list01[0:3]) # [1, 3, 5] # 增加資料到最後 a.append("apple") # ["apple"] a.append("banana") # ["apple", "banana"] # 指定位置加入 a.insert(1, "orange") # ["apple", "orange", "banana"] # 指定位置刪除資料 del list01[2] # 5 print(list01) # [1, 3, 7, 9, 11, 13] list01.pop(3) # 9 print(list01) # [1, 3, 7, 11, 13] # 指定要刪掉的值刪除 list01.remove(13) print(list01) # [1, 3, 7, 11] ``` #### 字典 (dict) >以 {key1:value, key2:value, ...} 來儲存多個key與value組合的型式 :::warning 想像成一般英漢字典單字(key)和解釋(value),解釋(value)可以重複但單字(key)不會重複 ::: ```python= # 創建新空dict的方式 dict01 = {} dict02 = dict() person = {'name': 'Amy', 'birthday': '8/26', 'age': 18, 'favorite_animal': 'cat'} # 找資料(用key尋找) print(person['name']) # 'Amy' print(person['favorite_animal']) # 'cat' # 增加資料 person['class'] = "3-A" print(preson) # {'name': 'Amy', 'birthday': '8/26', 'age': 18, 'favorite_animal': 'cat', 'class': '3-A'} # 刪除資料 del person['birthday'] print(preson) # {'name': 'Amy', 'birthday': '8/26', 'favorite_animal': 'cat', 'class': '3-A'} ``` :::info 除此之還有 **集合(Set)** 和 **元組(Tuple)** 兩種容器型態,但相較上面兩種較少使用,有興趣自行上網查 ::: ## 流程控制 :::warning 縮排 ( tab鍵 or 4個空格 ) 很重要!!!! 要一致喔!!!! ::: ### 條件型 #### if ```python= if 放條件: 放達成條件之後要執行的程式 ``` #### elif ```python= elif 第二個判斷條件: 執行的程式 ``` #### else ```python= else: 不符合其他條件,就執行的程式 ``` :::warning 一個條件區塊內,需有 if 開頭, elif 、 else 不能單獨使用,並且在此區內 if 、 else 只能有一個,一旦再次出現 if 便是新的條件區塊 ::: #### 範例 ```python= #成績等第判斷 grade = 80 # 如果成績大于90,則輸出 A if grade >= 90: print("A") # 如果成績大于80,則輸出 B elif grade >= 80: print("B") # 如果成績大于70,則輸出 C elif grade >= 70: print("C") # 如果成績都不符合上述條件(也就是小于70),則輸出 D else: print("D") ``` ### 迴圈型 #### for ```python= for 變數 in range(圈數): 要執行的程式 ``` #### 範例 ```python= # 每跑一次迴圈,i就會+1,總共會跑10次(0~9) for i in range(0,10): # 輸出i print(i) ``` #### while ```python= while 要執行此迴圈的條件: 執行的內容 ``` #### 範例 ```python= # 計數器的狀態 status = True #初始化計數器 i = 0 # 當計數器的狀態為True的時候,就不斷執行此迴圈,只到狀態不是True為止 while status == True: # 輸出計數 print(i) # 每跑一次迴圈就+1 i += 1 # 讓使用者決定是否要更改計數器的狀態 status = input("請輸入是否要繼續計數:") ``` ## 實作練習 ### LAB-01 https://www.codewars.com/kata/525f50e3b73515a6db000b83/train/python ![](https://i.imgur.com/YrlkF7Z.png) ### LAB-02 https://www.codewars.com/kata/54ff3102c1bad923760001f3/train/python ![](https://i.imgur.com/vl94PMA.png) ## 參考資料 * 土豆 (2020). Python 入門教學. Retrieved from: https://hackmd.io/GcikZaGORSqp4Xn-qHkhxg?view * oneone (2019). python basic. Retrieved from: https://slides.com/oneone/python_basic/ * oneone (2019). Python. Retrieved from: https://slides.com/oneone/python * 陳子晴 (2018). Python 初學第二講 — 資料型態與轉換. Retrieved from: https://medium.com/ccclub/ccclub-python-for-beginners-tutorial-d26900b9280e * Django Girls (無日期). Python 入門. Retrieved from: https://djangogirlstaipei.herokuapp.com/tutorials/python/?os=windows