# Python 基礎 ## @2022 NYCU_CS_CAMP --- # 環境 ---- ## Colab 1. 在瀏覽器中編寫及執行 Python 程式碼 2. 不用進行任何設定 3. 每日限額GPU使用量 4. 資工系窮學生寫作業的救星 ---- ## Usage ``` # 安裝python package !pip install [PACKAGE_NAME] # 在 apt install 前更新軟體庫清單 !apt-get update # 安裝軟體套件 !apt install [PACKAGE_NAME] ``` ---- ## 儲存格 ![](https://i.imgur.com/iADzngQ.png) ---- ## 執行儲存格 - 滑鼠:按儲存格左上角執行鍵 - 快捷鍵:Shift + Enter ---- ## 執行結果:computer: ![](https://i.imgur.com/GjKMJlx.png) --- # *Hello World!* ---- ## 輸出字串 ```python= # 直接印出 print(字串) ↑ 要印出的字串 # 格式化印出 print(字串.format()) ↑ 要印出的字串 ``` ---- ## 直接印出 ```python= # 包在單引號 '' 或 雙引號 "" 裡面即為字串 print("Hello, World!") ``` <p style="text-align:left; margin-left:50px; font-size:30px;">Output:</p> ```python= Hello, World! ``` ---- ## 格式化輸出 ```python= # 前面有多少組大括號{},format的括號()裡就要有多少個字串 print("{}, {}!".format("Hello", "World")) ``` <p style="text-align:left; margin-left:50px; font-size:30px;">Output:</p> ```python= Hello, World! ``` ---- ![](https://i.imgur.com/qfyosWC.jpg =750x) ---- ## 當你想要print單引號 ```python= # 錯誤示範 print('I'm Tom.') ``` ---- ## 執行結果 ![](https://i.imgur.com/NBmHyF3.png) ---- ## 單雙引號:computer: ```python= # 當你想要print單引號 # 方法1: 使用逃脫字元 \ (Backslash) print('I\'m Tom.') # 方法2: 雙引號 print("I'm Tom.") ``` <p style="text-align:left; margin-left:50px; font-size:30px;">Output:</p> ``` I'm Tom. I'm Tom. ``` ---- # 小隊討論時間 ## 3 minutes :::info 1. 如果字串同時包含單引號和雙引號? 2. 兩種輸出方式的差別 ::: ---- ## 智多星時間 :::danger 請印出下列字串 ``` "It's not my turn to cook," he said. ``` <br> ::: ---- ## 輸入字串 ```python= input(提示字) ↑ #在輸入前會印出這個字串 ``` ---- ## 輸入範例:computer: ``` # 不給提示字 print(input()) # 在輸入前會出現提示字 print(input("Please enter your name: ")) ``` <p style="text-align:left; margin-left:50px; font-size:30px;">Output:</p> ![](https://i.imgur.com/vEOryw5.png =500x) --- ## 註解 (comment) - 程式在執行時會忽略註解 - 用來增加程式可讀性以及後續的維護性 - 不同程式語言,相對的註解方式也不同 ---- ## 使用範例 ```python= # 單行註解 """ 多 行 註 解 """ ``` ---- ## 單行註解 ```python= # print("我是註解,不會被執行") print("我會被執行") ``` <p style="text-align:left; margin-left:50px; font-size:30px;">Output:</p> ``` 我會被執行 ``` ---- ## 多行註解 ```python= """ print("這些都不會") print("被執行") """ print("這個會執行") ``` <p style="text-align:left; margin-left:50px; font-size:30px;">Output:</p> ``` 這個會執行 ``` ---- # 小隊討論時間 ## 3 minutes :::info 1. 輸入前給予提示字的用意,不給的話會怎樣? 2. 註解在程式裡面的用處 ::: --- # 變數 ## (Variable) ---- ## 什麼是變數? - 一種用來儲存資料的容器 - 數字、字串等等都是可以被儲存的對象 - 用來進行各種運算的基礎 ---- ## 變數型態 | 變數型態 | 意思 | 例子 | | -------- | ------------ | ------------------------ | | int | 整數 | 1, 2, -53 | | float | 小數、浮點數 | 3.14159, -5.3, 0.0 | | str | 字串 | '出水芙蓉', '==', '' | | bool | 布林值 | True, False(首字母大寫) | ---- ## 引號 被引號包住的我們稱之為字串,字串是一連串的字 包含空格、數字、英文字母、中文或各式符號 Ex: <font color="#EF9F9F">'hello world'</font> , <font color="#FFCC8F">‘我是Allen’</font> , <font color="#FEF9A7">‘哇!!’</font> , <font color="#C2DED1">‘!@#$%^&*(())’</font> ---- ## 指派(assign) 意思是把等號右邊的東西存進左邊 <font color="#F47C7C">左邊只能是變數</font>,右邊可以是變數、數字、字串等 ![](https://i.imgur.com/KXa3lUE.png) ---- ![](https://i.imgur.com/YsCl2yx.png ) ---- ## 比較 | 表達式 | 數學上 | 程式上 | |:---------:|:------:|:------:| | x = 3 | V | V | | 3 = x | V | X | | x = x + 1 | X | V | | x = y | V | V | ---- ## 變數命名規則 - 字首不能為數字 - 可以使用底線( _ ) - 不能使用運算符號在變數名稱 - 不能使用保留字 - 可以用中文(但是不推薦) ---- ## python保留字 - 在python裡面已經有其他定義的關鍵字,因此被“保留”下來 - 所有在colab裡面預設被塗成<font color="#BAABDA">紫色</font>的字 - 不需要背 - 包含但不限於以下 ![](https://i.imgur.com/OHyl9S3.png =1000x) ---- ## 範例 ```python= # 合格範例 apple = 'rotten' user_id = 5 timeUsed = 60 # 錯誤範例 5 = five 3apples = 100 three+five = 8 ``` ---- ## 智多星+討論時間 :::danger 下列哪幾個變數名稱是不合法的? ```python= pleague+ = 'sbl' + 't1 league' _____ = 0.38 -_____- = 'sigh' true = 3 - 1 True = 3 - 1 My answer = 1234567 ``` <br> ::: ---- ## 建議命名方式 - 有意義的名稱 - 跟別人合作專案 - 未來可能會再用到這份程式碼 - Ex: result, numberOfCars, student_id ---- ### 蛇形命名法 (Snake Case) 單字皆為小寫,單字以底線_間隔 Ex: number_of_milk, cherry_left ---- ### 駝峰式命名法 (Camel Case) 第一個字母為小寫 之後每一個單字的開頭為大寫,不包含空格 Ex: totalApples, numberOfAvocado ---- ### 常數命名 全部用大寫,單字之間以底線_間隔 Ex: PI, PLANCK_CONSTANT, LIGHT_SPEED ---- ## 比較 | Snake Case | Camel Case | |:----------------- |:--------------- | | total_cost | totalCost | | word_tokenizer | wordTokenizer | | mean_square_error | meanSquareError | ---- ## 變數重複宣告 當同一個變數被宣告兩次以上便為重複宣告 ```python= x = 10 x = 'ten' print(x) ``` <p style="text-align:left; margin-left:50px; font-size:30px;">Output:</p> ``` ten ``` ---- ## Try it :::success 請問執行完之後x, y分別為多少? ```python= x = 15 y = 10 y = x + y x = y + 1 x = x + 3 y = y - 1 ``` <br> ::: ---- ## 執行結果 ![](https://i.imgur.com/UgukxED.png) --- # 算數運算子 ## (Arithmetic Operator) ---- ## 算術運算子 - 類似一般的加減乘除 - 先乘除後加減,括號要先算,答案會是數字 - 跟國小數學一樣!!!! ---- | 算術運算 | 運算子 | 範例 | 結果 | | ------------ | ------ | ------ | ---- | | 加法 | + | 1 + 2 | 3 | | 減法 | - | 5 - 3 | 2 | | 乘法 | * | 2 * 3 | 6 | | 除法 | / | 5 / 2 | 2.5 | | 下高斯除法⌊⌋ | // | 5 // 2 | 2 | | 次方 | ** | 2 ** 5 | 32 | | 取餘數 | % | 13 % 5 | 3 | ---- ## Try it :::success 請算出下列算式的解答,並印出來 ``` (30 - 25) * 50 / 8 + (99 % 35) ** 2 - 8888 // 75 ``` <br> ::: ---- ## 進階算數運算子:computer: 假設 x = 14 | 運算子 | 範例 |等同於| print(x) | | -------- | -------- | -------- | ---- | |+= | x += 1 | x = x + 1| 15 | |-= | x -= 5 | x = x - 5| 9 | |*= | x *= 3 |x = x * 3| 42| | /= | x /= 7 | x = x / 7| 2| ---- ## 字串的加法 ```python= print("pine" + "apple") ``` <p style="text-align:left; margin-left:50px; font-size:30px;">Output:</p> ```python= pineapple ``` ---- ## 數字加法 vs. 字串加法 | 數字加法 | 結果 | 字串加法 | 結果 | | ----------- | ---- | --------------- | -------- | | 3 + 5 | 8 | '3 + 5' | 3 + 5 | | 3.14 + 0.14 | 3.28 | '3.14' + '0.14' | 3.140.14 | | 三年 + A班 | 不合法 | '三年' + 'A班' | '三年A班' | ---- # 小隊討論時間 ## 3 minutes :::info 1. 為什麼變數要盡量使用有意義的名稱? 2. 算數運算子的優先順序 3. 數字加法 vs. 字串加法 ::: ---- ## 智多星時間 :::danger 1. 假設你有一筆93塊的帳單 2. 有20元、10元、5元和1元硬幣 3. 請用最少的硬幣數量支付你的帳單 4. 將各硬幣數量分別存入twenty, ten, five, one四個變數 5. 印出結果 ```python= bill = 93 twenty = bill "???" 20 # 請將"???"替換成一種算數運算子 bill = bill "???" 20 # 請將"???"替換成一種算數運算子 # Put your code here print("20元:", twenty, "\n10元:", ten, "\n5元:", five, "\n1元:", one) ``` <br> ::: --- # 關係運算子 ## (Comparison Operator) ---- ## 關係運算子 <br> - 判斷一件事情的真偽 - 只會有兩種結果,<font color="#EF9F9F">True 或 False </font> (1或0) ---- | 名稱 | 運算子 | 例子 | 結果 | | -------- | -------- | -------- | ---| | 大於 | > | 3 > 2 | True | | 小於 | < | 3 < 2 | False | | 不等於 | != | 3 != 2 | True | | 等於 | == | 3 == 2 | False | ---- ## 等於 vs. 等於等於 \ **=**:指派(assign)符號右邊的值給左邊 **==**:判斷符號兩側的數值是否相等 ---- ## Try it :::success 請問印出來的結果是什麼? ```python= print(1 == 1) print(4 < 2) print(3 != 6) print(5 > 2) ``` <br> ::: --- # 邏輯運算子 ## (Logical Operator) ---- ## 二元(binary)邏輯運算子 and(且) -- 左右兩者為真則命題為真,其餘為假 | X | Y | X and Y | |:-----:|:-----:|:-------:| | True | True | True | | True | False | False | | False | True | False | | False | False | False | ---- ## 舉例 ```python= 小孩子很受歡迎 且 他是智多星 => 小孩子很受歡迎 -> True 他是智多星 -> True ``` ---- ## 二元(binary)邏輯運算子 or(或) -- 左右其一為真則命題為真,其餘為假 | X | Y | X or Y | |:-----:|:-----:|:------:| | True | True | True | | True | False | True | | False | True | True | | False | False | False | ---- ## 舉例 ```python= 沒對到拍肯定是小田 或 阿伯在搞耍 小田和阿伯至少有一個人在搞耍 ``` ---- ## 一元(unary)邏輯運算子 not(非) -- 運算元為真則命題為假,反之為真 | X | not X | |:-----:|:-----:| | True | False | | False | True | ---- ## 舉例 ```python= 非黑即白 ``` --- # 成員運算子 ## (Membership Operator) ---- ## in & not in ```python= # 判斷列表是否存在某元素 print('Amber' in ['Joe', 'Jason', 'James']) # 判斷字串是否包含某字母/子字串 print('a' in 'apple') print('ap' not in 'apple') ``` <p style="text-align:left; margin-left:50px; font-size:30px;">Output:</p> ```python= False True False ``` ---- ## 優先級(由高到低) 1. 算術運算子(+) 2. 成員運算子(in)、關係運算子(>) 3. not 4. and 5. or ---- # 小隊討論時間 ## 3 minutes :::info 1. 等於 vs. 等於等於 2. and, or, not例子理解 3. in, not in可以用來判斷什麼? ::: ---- ## 智多星時間 :::danger 請判斷下列問題的真假 ```python= # Q1 print(True or False and False) # Q2 x = (3 == 2) == (4 == 5) y = True z = not y print(z and y or x) # Q3 print(not(True or (4 % 3 == 1 or False and 10//3 > 3))) ``` <br> ::: --- # 常用資料結構 ## (Data Structure) ---- ## 試著想像 ![](https://i.imgur.com/HASmXXH.jpg =800x) ---- ## 試著想像 ![](https://i.imgur.com/KGYeIvO.jpg =800x) ---- ## 資料結構 - 可以儲存很多很多相同或不同(*)型態的變數或常數 - ex: 數字、字串 ---- ## 性質 - 順序性(Ordered):若大容器的資料有<font color="#EF9F9F">先後順序</font>,新的東西會被放在最後面,則稱為有順序性 - 可更改的(Mutable):若大容器<font color="#EF9F9F">內容可以改變</font>,則稱為可更改的 ---- ## 索引(Index) Index指的是資料在大容器裡的位置 平常數數我們都是從1開始 但是在程式裡面一切都是<font color="#EF9F9F">從0開始</font> ![](https://i.imgur.com/Hjras01.png) ---- ![](https://i.imgur.com/QuMxYOR.jpg =700x) ---- ## 索引(Index) ```python= random_list = ['hi', 234, False, 4.5] # 取得index = 2的資料 print('random_list[2]:', random_list[2]) # 更改index = 3的資料 random_list[3] = 'modified' print('random_list:', random_list) ``` <p style="text-align:left; margin-left:50px; font-size:30px;">Output:</p> ``` random_list[2]: False random_list: ['hi', 234, False, 'modified'] ``` ---- ## 取得子字串 ```python= 最後index為長度-1 ↓ 'substring' ↑ 開頭index為0 ``` ---- ## 取得子字串 ```python= stringVar[k] ↑ 取得index為k的字 stringVar[k:j] ↑ 取得index在k到j-1之間的子字串 stringVar[::-1] ↑ 取得翻轉過後的字串 ``` ---- ## 範例 ```python= name = 'Andy Dufresne' # 取得某字母 print(name[6]) # 取得子字串 print(name[0:4]) # 取得翻轉過後的字串 print(name[::-1]) ``` <p style="text-align:left; margin-left:50px; font-size:30px;">Output:</p> ```python= u Andy enserfuD ydnA ``` ---- ## 列表(List) - 用中括號[]或list()宣告資料型態 - list是有順序性(Ordered)也可變動(Mutable)的 ```python= # 宣告方法 list_of_things = ['apple', 55688, True, [1, 2, 4]] random_list = list() ``` ---- ## 從列表新增、移除元素 ```python= list_of_things = ['apple', 55688, True, [1, 2, 4]] # 新增元素至列表 list_of_things.append('student') list_of_things.append('teacher') # 從列表移除元素 list_of_things.remove(55688) print(list_of_things) ``` <p style="text-align:left; margin-left:50px; font-size:30px;">Output:</p> ```python= ['apple', True, [1, 2, 4], 'student', 'teacher'] ``` ---- ## Try it :::success 1. 請先定義一個列表名為list_of_things,如下 2. 找到index = 3的值 3. 印出結果 ```python= list_of_things = ['apple', 55688, True, [1, 2, 4]] # Put your code here ``` <br> ::: ---- ## 元組(Tuple) - 用小括號( )或tuple()宣告資料型態 - Tuple是有順序性(Ordered)但不可變動(Unmutable)的,所以沒辦法增加、刪除或更改東西 ```python= # 宣告方法 location_a = (13.4125, 103.866667) random_tuple = tuple() ``` ---- ## Try it :::success 1. 請先定義一個元組名為location,如下 2. 先印出location中index = 0的值 3. 將location中index = 0的值改為25.29 ```python= location = (13.4125, 103.866667) # Put your code here ``` <br> ::: ---- ![](https://i.imgur.com/bDMxDOM.jpg) ---- ## 集合(Set) - Set儲存的數值不會重複 - 用大括號{}或set()宣告資料型態 - Set沒有順序性(Unordered)但可變動(Mutable) ```python= # 宣告方法 i_am_set = {3, 1, 53, 1, 1} # 也可以由list轉成set list_of_num = [1, 2, 6, 3, 1, 1, 6] set_of_num = set(list_of_num) ``` ---- ## 集合(Set) ```python= # 宣告方法 i_am_set = {3, 1, 53, 1, 1} # 也可以由list轉成set list_of_num = [1, 2, 6, 3, 1, 1, 6] set_of_num = set(list_of_num) print('i_am_set:', i_am_set) print('set_of_num:', set_of_num) ``` <p style="text-align:left; margin-left:50px; font-size:30px;">Output:</p> ```python= i_am_set: {1, 3, 53} set_of_num: {1, 2, 6, 3} ``` ---- ## 從集合新增、移除元素 ```python= i_am_set = {3, 1, 53, 1, 1} # 新增元素到集合 i_am_set.add(8) # 從集合當中移除元素 i_am_set.remove(1) print('i_am_set:', i_am_set)` ``` <p style="text-align:left; margin-left:50px; font-size:30px;">Output:</p> ```python= i_am_set: {8, 3, 53} ``` ---- ## Try it :::success 1. 請先定義一個集合名為set_of_num,如下 2. 印出set_of_num中index = 3的值 ```python= set_of_num = {1, 2, 3, 6} # Put your code here ``` <br> ::: ---- ## 字典(Dictionary) - 儲存方法為 key : value,用key搜尋value - 用大括號{}或dict()宣告資料型態 - Dictionary是沒有順序性(Unrdered)但可變動(Mutable)的 ```python= # 宣告方式 element_dict = {"hydrogen": 1, "helium": 2, "carbon": 6} i_am_dict = dict() # 印出key=helium時的value print(element_dict['helium']) ``` <p style="text-align:left; margin-left:50px; font-size:30px;">Output:</p> ```python= 2 ``` ---- # 小隊討論時間 ## 3 minutes :::info 1. 大容器的作用 2. 大容器能不能放在一個更大的容器裡面 3. 列表、元組、集合、字典的使用場景 ::: ---- ## Try it :::success 1. 請先定義一個字典名為element,資料如下 2. 印出key='C'的value | key | value | |:---:|:-----:| | 'H' | 1 | | 'C' | 12 | | 'N' | 14 | ```python= element = dict() # Put your code here ``` <br> ::: ---- ## 智多星時間 :::danger 1. 請先定義一個列表名為random_list,如下 2. 試著取得'target'所在的位置 3. 印出結果 ```python= # HINT: 會需要兩個索引(index) random_list = ['hi', 234, False, (1, 'target', 5)] ``` <br> ::: --- # 條件 ## (Condition) ---- ## 縮排 * 用來區分程式區塊 * <font color="#EF9F9F">同一個區塊內縮排必須一致</font> (統一使用空格或tab) * 空格的話習慣用四個空格當作縮排 ![](https://i.imgur.com/x4FU2Qd.png =400x) ---- ## 試著想像 ![](https://i.imgur.com/MCe2XcZ.png =500x) ---- ## 如果...就...(v1.0) ```python= 該條件成立時 執行程式碼 ↓ if 條件: 程式碼 ``` ---- ## 流程圖 ![](https://i.imgur.com/8D1wcxZ.png =700x) ---- ## 範例 ```python= numberOfAvocado = 3 if numberOfAvocado > 0: print("買六加侖牛奶") ``` <p style="text-align:left; margin-left:50px; font-size:30px;">Output:</p> ``` 買六加侖牛奶 ``` ---- ## 縮排錯誤範例 ```python= # 沒縮排 if True: print("我沒有縮排") ``` ---- ## 執行結果:computer: ![](https://i.imgur.com/anMnLks.png) ---- ## 縮排錯誤範例 ```python= # 縮排不一致 if True: print("我用tab縮排") print("我用兩個空格縮排") ``` ---- ## 執行結果:computer: ![](https://i.imgur.com/wWBIGmk.png) ---- ## 如果...就...否則就...(v2.0) ```python= 該條件成立時 執行程式碼1 ↓ if 條件: 程式碼1 else: 程式碼2 ↑ 否則執行程式碼2 ``` ---- ## 流程圖 ![](https://i.imgur.com/qCUhlEC.png =750x) ---- ## 範例 ```python= numberOfAvocado = 3 if numberOfAvocado > 0: print("買六加侖牛奶") else: print("買一加侖牛奶") ``` <p style="text-align:left; margin-left:50px; font-size:30px;">Output:</p> ``` 買六加侖牛奶 ``` ---- ## 如果...就...否則如果...就...(v2.0.1) ```python= if 條件1: 程式碼1 elif 條件2: 程式碼2 elif 條件3: 程式碼3 . . . ``` ---- ## 流程圖 ![](https://i.imgur.com/FALkdbV.png =700x) ---- ## 範例 ```python= # A list with 3 elements condition = [False, False, True] if condition[0]: print("condition0 is True") elif condition[1]: print("condition1 is True") elif condition[2]: print("condition2 is True") ``` <p style="text-align:left; margin-left:50px; font-size:30px;">Output:</p> ```python= condition2 is true ``` ---- ## 如果...就...否則如果...就...否則就...(完全版) ```python= if 條件1: 程式碼1 elif 條件2: 程式碼2 else: 程式碼3 ``` ---- ## 流程圖 ![](https://i.imgur.com/jURljur.png =700x) ---- ## 範例 ```python= # A list with 3 elements condition = [False, False, False] if condition[0]: print("condition0 is True") elif condition[1]: print("condition1 is True") elif condition[2]: print("condition2 is True") else: print("conditions are all False") ``` <p style="text-align:left; margin-left:50px; font-size:30px;">Output:</p> ```python= conditions are all false ``` ---- # 小隊討論時間 ## 3 minutes :::info 1. 縮排的用處,沒縮排在程式上會有什麼問題?(除了會跳error之外) 2. 試舉例何時該使用v1.0條件句、何時該使用v2.0條件句... ::: --- # 迴圈(loop) ---- ## for 迴圈 ```python= 給予迴圈的範圍 ↓ for 變數 in 迭代目標: 程式碼 ``` ---- ## 流程圖 ![](https://i.imgur.com/w6wpkc8.png =750x) ---- ## 範例 ```python= # Case1: range # 在迴圈內沒用到變數i for i in range(5): print("一代") ``` <p style="text-align:left; margin-left:50px; font-size:30px;">Output:</p> ```python= 一代 一代 一代 一代 一代 ``` ---- ## 範例 ```python= # Case1: range # 在迴圈內用到變數i total = 0 # i從0,1,2...,100 for i in range(101): total += i print(total) ``` <p style="text-align:left; margin-left:50px; font-size:30px;">Output:</p> ```python= 5050 ``` ---- ## 範例 ```python= # Case2: iterate list intList = [0,1,2] for i in intList: print(i) ``` <p style="text-align:left; margin-left:50px; font-size:30px;">Output:</p> ```python= 0 1 2 ``` ---- ![](https://i.imgur.com/ygA5y8h.png =670x) ---- # 小隊討論時間 ## 3 minutes :::info 1. 迭代目標可以有哪些? 2. for迴圈何時終止? ::: ---- ## Try it :::success 1. 請先初始化一個字串變數name,初始化的值為[你/妳的英文名字] 2. 以name為迭代(iterate)目標跑for迴圈並印出i 3. 觀察結果 ::: ---- ## 智多星時間 :::danger 1. 每個英文字母代表一個分數,分數定義如下 2. 請試著用for迴圈計算string裡面英文字母的分數和,並存至total 3. Ex: fox = 20 + 5 + 20 = 45 ```python= # 分數用字典定義 score = {5:'aeinostu', 10:'bcmprlg', 20:'fhvwykjxqzd'} # 欲計算的字串變數 string = 'girlfriend' total = 0 # 總分 # HINT: 你可能會用到 in # Put your code here print("{}: {}".format(string, total)) ``` ::: ---- ## while 迴圈 ```python= 每次迴圈會判斷 條件是否成立 ↓ while 條件: 程式碼 ``` ---- ## 流程圖 ![](https://i.imgur.com/tfeRbcw.png =750x) ---- ## 範例 ```python= # 跨年倒數 timer = 5 while timer > 0: # str(變數): 將變數資料型態轉為字串 print(str(timer) + '!') timer -= 1 print("Happy New Year!") ``` <p style="text-align:left; margin-left:50px; font-size:30px;">Output:</p> ```python= 5! 4! 3! 2! 1! Happy New Year! ``` ---- ## 無窮迴圈(infinite loop) ```python= # 跨年倒數器 timer = 5 while timer > 0: # str(變數): 將變數資料型態轉為字串 print(str(timer) + '!') # timer -= 1 print("Happy New Year!") ``` ---- ## 執行結果:computer: 可以執行看看 然後在你/妳電腦爆炸之前按下停止鍵 ---- ![](https://i.imgur.com/kuZ7vTD.jpg) ---- ## 寫成程式碼:computer: ```python= atStore = True while atStore: print("Get some milk") ``` <p style="text-align:left; margin-left:50px; font-size:30px;">Output:</p> ```python= Get some milk Get some milk Get some milk . . . ``` ---- # 巢狀迴圈 ## nested loop ---- ## 試著想像 ![](https://i.imgur.com/QspEwjC.png =500x) ---- ## 單層for迴圈 ```python= for i in range(1,10): print("1 * " + str(i) + " = " + str(1*(i))) for i in range(1,10): print("2 * " + str(i) + " = " + str(2*(i))) for i in range(1,10): print("3 * " + str(i) + " = " + str(3*(i))) for i in range(1,10): print("4 * " + str(i) + " = " + str(4*(i))) for i in range(1,10): print("5 * " + str(i) + " = " + str(5*(i))) for i in range(1,10): print("6 * " + str(i) + " = " + str(6*(i))) for i in range(1,10): print("7 * " + str(i) + " = " + str(7*(i))) for i in range(1,10): print("8 * " + str(i) + " = " + str(8*(i))) for i in range(1,10): print("9 * " + str(i) + " = " + str(9*(i))) ``` ---- ## 巢狀迴圈寫法 ```python= for i in range(1,10): for j in range(1,10): print(str(i) + " * " + str(j) + " = " + str(i*j)) ``` <p style="text-align:left; margin-left:50px; font-size:30px;">Output:</p> ```python= 1 * 1 = 1 1 * 2 = 2 . . . 9 * 8 = 72 9 * 9 = 81 ``` ---- ## 如果... - 我要用更多層迴圈? ✔︎ - 我要同時用for跟while迴圈? ✔︎ ---- # 小隊討論時間 ## 3 minutes :::info 1. for迴圈和while迴圈的差別 2. while迴圈何時終止? 3. 還有哪些時候會用到巢狀迴圈? ::: ---- ## 智多星時間 :::danger 1. 定義4*4 treasureMap如下,其中有一處為寶藏 2. 請用雙層for迴圈找到寶藏在第幾列第幾行,並分別指派給變數treasureRow, treasureCol ```python= import random random.seed(105) treasureMap = [["stone","stone","stone","stone"], ["stone","stone","stone","stone"], ["stone","stone","stone","stone"], ["stone","stone","stone","stone"]] treasureMap[random.randint(0,3)][random.randint(0,3)] = "treasure" # Put your code here print("Treasure map:") for i in range(4): print(treasureMap[i]) print("\nTreasure row:", treasureRow, "\nTreasure column:", treasureCol) ``` <br> ::: ---- # continue & break ---- ## 試著「迴」憶 ```python= for i in range(5): print("Round:", i) ``` <p style="text-align:left; margin-left:50px; font-size:30px;">Output:</p> ```python= Round: 0 Round: 1 Round: 2 Round: 3 Round: 4 ``` ---- ## continue範例 ```python= for i in range(5): if i == 2: continue print("Round:", i) ``` <p style="text-align:left; margin-left:50px; font-size:30px;">Output:</p> ```python= Round: 0 Round: 1 Round: 3 Round: 4 ``` ---- ## break範例 ```python= for i in range(5): if i == 2: break print("Round:", i) ``` <p style="text-align:left; margin-left:50px; font-size:30px;">Output:</p> ```python= Round: 0 Round: 1 ``` --- # 函式 ## function ---- ## 試著想像 ![](https://i.imgur.com/z16IXAW.jpg =650x) ---- ## 試著想像 ![](https://i.imgur.com/PW1Kpoa.jpg =650x) ---- ## 試著想像 ![](https://i.imgur.com/c54SXtL.jpg =650x) ---- ## 假如用前面學到的 ```python= # 第一步 print("Open door") # 第二步 print("Put into fridge") # 第三步 print("Close door") ``` ---- ## 試著想像 ![](https://i.imgur.com/nlyZktZ.jpg =650x) ---- ## 假如用前面學到的 ```python= for i in range(100): # 第一步 print("Open door") # 第二步 print("Put into fridge") # 第三步 print("Close door") ``` ---- ## 試著想像 ![](https://i.imgur.com/nq49R5k.jpg =600x) ---- ## 試著想像 ![](https://i.imgur.com/0Lu67CG.png =600x) ---- ## 參數&回傳值 - y = f (x) - f為function - x為參數 - y為回傳值 ---- ## 函式介紹 - 呼叫前必須先定義過 - 可由自己自行定義 - 定義時可以給予參數,可以有回傳值 - 呼叫時依照定義給予對應參數數量,並接收回傳值 ---- ## 定義函式 ```python= def 函式名稱(參數): 程式碼 ``` ---- ## 定義函式 ```python= # 開頭 def 代表要定義一個新函式 def ``` ---- ## 定義函式 ```python= # 加上函式名稱(命名規則跟變數一樣,建議皆使用英文) def 函式名稱 ``` ---- ## 定義函式 ```python= # 加上括號代表他是一個函式 def 函式名稱() ``` ---- ## 定義函式 ```python= # 加上參數 # 參數外用小寫括號包起來 def 函式名稱(參數) ``` ---- ## 定義函式 ```python= # 也可以有多個參數 # 參數間用小寫逗號隔開 def 函式名稱(參數1, 參數2, 參數3) ``` ---- ## 定義函式 ```python= # 加上小寫冒號 def 函式名稱(參數): ``` ---- ## 定義函式 ```python= # 加上程式碼 # 以縮排決定函式的區塊 def 函式名稱(參數): # 這裡在函式內 程式碼 ``` ---- ## 定義函式 ```python= # 加上程式碼 # 以縮排決定函式的區塊 def 函式名稱(參數): # 這裡在函式內 程式碼 # 這裡不在函式內 程式碼 ``` ---- ## 定義函式 ```python= def 函式名稱(參數): 程式碼 # 可以加回傳值,回傳值前必須加上 return return 回傳值 ``` ---- ## 呼叫函式 ```python= 函式名稱(參數) ``` ---- ## 呼叫函式 ```python= # 定義無參數函式 def 函式名稱(): 程式碼 # 呼叫時參數數量取決於定義時的參數數量 函式名稱() ``` ---- ## 呼叫函式 ```python= # 定義單參數函式 def 函式名稱(參數): 程式碼 # 呼叫時參數數量取決於定義時的參數數量 函式名稱(參數) ``` ---- ## 呼叫函式 ```python= # 定義多參數函式 def 函式名稱(參數1, 參數2, 參數3): 程式碼 # 呼叫時參數數量取決於定義時的參數數量 函式名稱(參數1, 參數2, 參數3) ``` ---- # 小隊討論時間 ## 3 minutes :::info 1. 如何定義函式、如何呼叫函式? 2. ~~如何把大象放進冰箱?~~ ::: ---- ## 函式範例 ```python= def printUnit(): # 沒有回傳值 print(1.0) def unit(): # 有回傳值 return 1.0 # 直接用函式印出 printUnit() # 將回傳值指派給變數 result = unit() print(result) ``` <p style="text-align:left; margin-left:50px; font-size:30px;">Output:</p> ```python= 1.0 1.0 ``` ---- ## 函式範例 ```python= # 單參數函式 def removeSpace(string): result = "" for i in string: if i != " ": result += i return result print(removeSpace(" Hello, world! This is Mike! ")) ``` <p style="text-align:left; margin-left:50px; font-size:30px;">Output:</p> ```python= Hello,world!ThisisMike! ``` ---- ## 函式範例 ```python= # 多參數函式 def multiplyString(string1, string2): return len(string1) * len(string2) print(multiplyString("three", "four")) ``` <p style="text-align:left; margin-left:50px; font-size:30px;">Output:</p> ```python= 20 ``` ---- ## 內建函式 - python內建的函式庫 - 因為已經定義過,使用時直接呼叫即可 ![](https://i.imgur.com/0PFyMO7.png =580x) ---- ## 內建函式範例 ```python= # 字串長度 print(len("string length")) # 取絕對值 print(abs(-3.14)) # 取最大值 print(max([3,5,7,4,1])) ``` <p style="text-align:left; margin-left:50px; font-size:30px;">Output:</p> ```python= 13 3.14 7 ``` ---- ## 內建函式範例 ```python= print(1 + 2) # 型別轉換 # int->float print(float(1) + float(2)) # int->str print(str(1) + str(2)) ``` <p style="text-align:left; margin-left:50px; font-size:30px;">Output:</p> ```python= 3 3.0 12 ``` ---- ## 用參數微調細節 ```python= def putElephantIntoFridge(degree): # 第一步 print("Open door") # 第二步 print("Put into fridge,", "degree =", degree) # 第三步 print("Close door") ``` ---- ## 用參數微調細節 ```python= putElephantIntoFridge(50) print("") # 空行 putElephantIntoFridge(5) ``` <p style="text-align:left; margin-left:50px; font-size:30px;">Output:</p> ```python= Open door Put into fridge, degree = 50 Close door Open door Put into fridge, degree = 5 Close door ``` ---- # 小隊討論時間 ## 3 minutes :::info 1. 參數的作用 2. 為何內建函式可以直接呼叫使用? ::: ---- ## 智多星時間 :::danger 1. 請完成palindrome(string)函式,如下頁所示 2. 判斷傳入字串是否為palindrome(迴文)並回傳 3. 在忽略空格的情況下,若一個字串從左邊讀和從右邊讀的字母順序都一樣,稱為palindrome 4. Ex: "never odd or even" 是palindrome &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"i am emma" 不是palindrome ::: ---- ## 智多星時間 :::danger <br> ```python= def palindrome(string): # Put your code here 程式碼 return isPalindrome strings = ["was it a car or a cat i saw", "eva can i see bees on a cave"] for string in strings: if palindrome(string): print("\"{}\"".format(string), "is palindrome.") else: print("\"{}\"".format(string), "is not palindrome.") ``` <br> ::: ---- ## 試著想像 ![](https://i.imgur.com/phYq1GD.jpg =600x) ---- ## 遞迴函式 ```python= def putElephantIntoFridge(numberOfFridge): print("Open door", numberOfFridge) if numberOfFridge == 1: print("Put into fridge", numberOfFridge) else: putElephantIntoFridge(numberOfFridge-1) print("Put fridge", numberOfFridge-1, "into fridge", numberOfFridge) print("Close door", numberOfFridge) ``` ---- ## 遞迴函式 ```python= putElephantIntoFridge(1) ``` <p style="text-align:left; margin-left:50px; font-size:30px;">Output:</p> ```python= Open door 1 Put into fridge 1 Close door 1 ``` ---- ## 遞迴函式 ```python= putElephantIntoFridge(2) ``` <p style="text-align:left; margin-left:50px; font-size:30px;">Output:</p> ```python= Open door 2 Open door 1 Put into fridge 1 Close door 1 Put fridge 1 into fridge 2 Close door 2 ``` ---- ## 遞迴函式 ```python= putElephantIntoFridge(3) ``` <p style="text-align:left; margin-left:50px; font-size:30px;">Output:</p> ```python= Open door 3 Open door 2 Open door 1 Put into fridge 1 Close door 1 Put fridge 1 into fridge 2 Close door 2 Put fridge 2 into fridge 3 Close door 3 ``` ---- ## 示意圖 ![](https://i.imgur.com/nhwa3zb.png =650x) ---- ## 模組化 ```python= def openDoor(): 程式碼 def putIntoFridge(): 程式碼 def closeDoor(): 程式碼 def putElephantIntoFridge(): openDoor() putIntoFridge() closeDoor() ``` ---- ## 更多遞迴函式範例 ```python= # 階層函數 ex: 3! = 1*2*3 def factorial(n): if n = 0: return 1 else: return n * factorial(n - 1) ``` ---- # 小隊討論時間 ## 3 minutes :::info 1. 接續上個例子,階層函式有先判斷是否n等於0,為什麼要這麼做? 2. 模組化的好處 ::: ---- ## 智多星時間 :::danger 1. 請先定義一遞迴函式名為fibonacci,有一個參數n,如下 2. 利用前面學到的遞迴概念完成此函式程式碼區塊,並回傳第n+1項費氏數列 3. 請用for迴圈印出前10項費氏數列 4. 費氏數列定義: f(n) = f(n-1) + f(n-2), f(0) = 0, f(1) = 1 ::: ---- ## 智多星時間 :::danger <br> ```python= # HINT:前10項費氏數列為0, 1, 1, 2, 3, 5, 8, 13, 21, 34 def fibonacci(n): # Put your code here result = [] for i in range(10): result.append(fibonacci(i)) print(result) ``` <br> ::: ---- ## 使用函式的好處 1. 重複利用性 2. 易讀性 3. 易除錯性 4. 模組化 5. 遞迴函式 --- # 常用函式庫 ---- ## numpy - 處理矩陣運算 - 矩陣相加、相乘、轉置矩陣 ```python= # 直接載入模組 import numpy # 常用別名 import numpy as np ``` ---- ## 範例 ```python= import numpy as np # 用二維陣列初始化 A = np.array([[1,1,1],[2,2,2]]) B = np.array([[1,2,3],[1,2,3]]) print(A + B) print(A - B) ``` <p style="text-align:left; margin-left:50px; font-size:30px;">Output:</p> ```python= [[2 3 4] [3 4 5]] [[0 -1 -2] [1 0 -1]] ``` ---- ## random - 產生亂數 - 隨機整數(int)、浮點數(float) - 隨機字元、隨機元素(列表內) ```python= import random ``` ---- ## 範例 ```python= import random random.seed(10) # random seed 是為了讓每次的執行結果一樣 print(random.randint(1,5)) # 1到5隨機整數 print(random.random()) # 0到1隨機浮點數 print(random.uniform(3.3,5.4)) # 3.3到5.4隨機浮點數 print(random.choice(['網球', '籃球', '足球'])) # 列表隨機元素 ``` <p style="text-align:left; margin-left:50px; font-size:30px;">Output:</p> ```python= 5 0.032585065282054626 4.313379516556798 網球 ``` ---- ## ![](https://i.imgur.com/ywo0YUn.png) ---- ## pandas - 數據操作 - 表格化 - 資料增減、排序 ```python= # 直接載入模組 import pandas # 常用別名 import pandas as pd ``` ---- ## 範例 ```python= import pandas as pd class_member = {"student_id":["0716001", "0816002", "0616003", "0716003"], "name":["Jenny", "Tom", "Jennifer", "Elon Musk"], "gender":["女", "男", "女", "男"], "grade":["大四", "大三", "大五", "大四"]} df = pd.DataFrame(class_member) df.head() ``` <p style="text-align:left; margin-left:50px; font-size:30px;">Output:</p> ![](https://i.imgur.com/igj98q4.png =500x) ---- ## matplotlib - 繪圖、視覺化工具 - 折線圖、柱狀圖 ```python= # 直接載入模組 import matplotlib.pyplot # 常用別名 import matplotlib.pyplot as plt ``` ---- ## 範例 ```python= # 為了使用numpy的array資料型態 import numpy as np import matplotlib.pyplot as plt item = np.array(["Apple", "Lemon", "Orange", "Pineapple"]) number = np.array([10, 3, 6, 1]) # 柱狀圖 -> 橫軸:item 縱軸:number plt.bar(item, number) plt.show() ``` <p style="text-align:left; margin-left:50px; font-size:30px;">Output:</p> ![](https://i.imgur.com/nFQWGFW.png =300x) --- # Last but not least ---- ## 有些錯誤很直觀 ![](https://i.imgur.com/3PjVEeM.png) ---- ## 但並不是總是如此:computer: ```python= subtotal = input("税前總額:") tax = 0.08 * subtotal print(subtotal,"需付的稅金為:", tax) ``` ---- ## 但並不是總是如此 ![](https://i.imgur.com/mAMKGvZ.png) ---- ## 估狗 ![](https://i.imgur.com/QOgxbFG.png =900x) ---- ## 估狗結果 ![](https://i.imgur.com/cDaPzUK.png) ---- ## 為什麼錯誤 ![](https://i.imgur.com/mAMKGvZ.png) ---- ## 修正後:computer: ```python= subtotal = input("税前總額:") tax = 0.08 * float(subtotal) print(subtotal,"需付的稅金為:", tax) ``` ---- ## 常用論壇 - Stack Overflow(Eng) - GeeksforGeeks(Eng) - CSDN(簡字) ---- ## 謝謝大家❤️ ![](https://i.imgur.com/oCtetbu.png =500x)
{"metaMigratedAt":"2023-06-17T04:27:31.337Z","metaMigratedFrom":"YAML","title":"Python 基礎","breaks":true,"contributors":"[{\"id\":\"5eabf723-793d-48fd-8620-672382fe8326\",\"add\":6,\"del\":14},{\"id\":\"99ef66e9-65ea-4c1e-ae46-b0bfd2c57acc\",\"add\":497,\"del\":5618}]"}
    968 views
   Owned this note