While 迴圈
## Python `while` 迴圈
`while` 迴圈會在指定條件為 `True` 時,重複執行程式區塊。當條件變成 `False`,迴圈就會結束。
### 語法
```python
while 條件:
執行的程式敘述
```
注意:Python 使用縮排表示迴圈內容。
### 基礎範例
```python
count = 1
while count <= 5:
print(count)
count += 1
```
輸出:
```text
1
2
3
4
5
```
在每次迴圈中,`count` 會加 1,當 `count` 大於 5 時,條件不成立,迴圈結束。
---
## `break` 指令
`break` 用來**立即結束目前的迴圈**,即使迴圈條件仍然成立,也不會繼續執行。
### 範例 1:使用 `break` 找到指定數字
```python
number = 1
while number <= 10:
if number == 5:
break
print(number)
number += 1
```
輸出:
```text
1
2
3
4
```
當 `number` 等於 5 時,執行 `break`,迴圈立即結束。
---
## `continue` 指令
`continue` 用來**跳過本次迴圈剩餘的程式敘述**,直接進入下一次迴圈。
### 範例 2:跳過偶數
```python
number = 0
while number < 10:
number += 1
if number % 2 == 0:
continue
print(number)
```
輸出:
```text
1
3
5
7
9
```
當 `number` 是偶數時,執行 `continue`,因此不會執行 `print(number)`,直接進入下一輪迴圈。
相關學習地圖、教學課程
Python 資料工程
Python 後端工程、資料庫