# 迴圈 Ⅰ ### 114/10/3 ### 講師:昱山 --- ## `while` 迴圈 ---- `while` 的意義如同圖中的積木 ![image](https://hackmd.io/_uploads/SyL5GBH2eg.png) 當布林值為 `True` 程式會持續執行, 直到布林值轉變為 `False` 。 ---- 格式: ```python= while [布林值]: ~要重複執行的程式~ ``` 範例: ```python= a = 10 while a > 0: a -= 1 print(a) ``` ---- 若條件沒設好,會導致程式無法停止。 ```python= a = 1 while a > 0: print(a) a += 1 ``` 此時可在終端機按下`Ctrl` + `C`以中斷程式 ---- 按下 `Ctrl` + `C` 會觸發 `KeyboardInterrupt` ![image](https://hackmd.io/_uploads/rJP2p-U2xe.png) --- ## `for` 迴圈 ---- 格式: ```python= for [變數] in [序列]: ~要重複執行的程式~ ``` 範例: ```python= for _ in range(5) print("你好") ``` ---- ### 什麼是序列(sequence)? ---- ### A:序列為包含多個元素的資料結構 ### `陣列(Array)`、`range()`……屬於序列 ### 本週會介紹`range()`的用法 ---- #### 【補充】以下皆屬於陣列(Array) <table class="table table-bordered bg-white text-center border-c" style="color: #333333; border: 1px solid #58595a;" data-darkreader-inline-color="" data-darkreader-inline-border-top="" data-darkreader-inline-border-right="" data-darkreader-inline-border-bottom="" data-darkreader-inline-border-left=""> <tr> <td>中文</td> <td>英文</td> <td>範例</td> </tr> <tr> <td>串列</td> <td>List</td> <td>[1, 2, 3]</td> </tr> <tr> <td>元組</td> <td>Tuple</td> <td>(1, 2, 3)</td> </tr> <tr> <td>集合</td> <td>Set</td> <td>{1, 2, 3}</td> </tr> <tr> <td>字典</td> <td>Dictionary</td> <td>{"1" : "小明", "2" : "小美" }</td> </tr> </table> 先看看就好 之後會更詳細地解說 --- ## range(a, b, c) ---- <img src=https://hackmd.io/_uploads/BJgACjLPUlx.png> ---- ### i 的意義:執行第i次 ```python= for i in range(5): print(i) ``` 這樣會輸出什麼呢? ---- 輸入 ```python= for i in range(5): print(i) ``` 輸出: ```bash 0 1 2 3 4 ``` ---- ![image](https://hackmd.io/_uploads/BJgACjLPUlx.png) ```python= for i in range(1, 10 ,3): print(i) ``` 輸出: ``` 1 4 7 ``` ---- ### 結論 - i 不會碰到 b --- ## `break` 與 `continue` ---- `break`:跳脫迴圈 `continue`:跳脫這一輪 ---- ```python= for i in range(7): if i == 5: continue print(i) #輸出為0 1 2 3 4 6 #跳過5 ``` ```python= for i in range(10): if i == 5: break print(i) #輸出為0 1 2 3 4 #5以後的數字不會輸出 ``` ---- 有了`break` 與 `continue`, 就可以安心使用 `while True:` 迴圈了 (重複無限多次) ```python= a = 6 while True: # 也可以寫成「while 1:」 a *= 6 print(a) if a > 100: print("已超過100") break ``` --- ### 練習題 [`a147.`](https://zerojudge.tw/ShowProblem?problemid=a147) [`a148.`](https://zerojudge.tw/ShowProblem?problemid=a148) [`d189.`](https://zerojudge.tw/ShowProblem?problemid=d189) ---- 備註:打好`d189.`後,須將程式放在以下的註解地方 ```python while True: try: ''' 將無限迴圈的判斷打在這裡 ''' except EOFError: break ``` ###### 其實這題只要知道公式就可以偷吃步 --- ## 預告 段考後(`10/17`)將舉行社內賽 共有三題,範圍為目前教過的內容 ---
{"description":"image","title":"迴圈 Ⅰ","contributors":"[{\"id\":\"b831f9fa-52bb-4a09-bfbb-148e4fdadd0f\",\"add\":3168,\"del\":350,\"latestUpdatedAt\":1759501707158}]"}
    136 views