---
title: "Loop-while loop 迴圈 (tc)"
description: while 迴圈：條件成立就一直跑——計數器跑 5 次、input() 一直問到 q 兩個例子。
url: "https://aaronchan.com/zh/kb/python-while-loop/"
updated: "2026-09-15"
category: "Code-Python (tc)"
tags:
  - python
---

# Loop-while loop 迴圈 (tc)

在不知道要重複幾次的時候，用 `while` 迴圈——只要條件成立就一直跑，直到條件不成立才停。下面兩個例子：一個用計數器跑 5 次，一個用 `input()` 一直問到輸入 `q` 才停。

## Example 1：計數器 — 跑 5 次

 Copy

```
count = 1

while count <= 5:
    print("Count is:", count)
    count += 1
```

**output:**

```
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
```

---

## Example 2：一直問到輸入 q — break 跳出

 Copy

```
while True:
    user_input = input("Enter 'q' to quit: ")
    if user_input == "q":
        print("Bye!")
        break
```

**output:**

```
Enter 'q' to quit: hello
Enter 'q' to quit: world
Enter 'q' to quit: q
Bye!
```
