1. 什么是 while 循环? #

count = 1
while count <= 5:
    print(count)
    count += 1      # 必须更新条件相关变量,否则会死循环

2. 基本语法 #

while 条件:
    # 循环体(缩进 4 空格)

3. break 与 continue #

语句 作用
break 立即结束整个循环
continue 跳过本次剩余代码,进入下一轮
n = 0
while n < 10:
    n += 1
    if n % 2 == 0:
        continue    # 跳过偶数
    if n > 5:
        break       # 大于 5 就结束
    print(n)

4. 常见模式:while True + break #

while True:
    choice = input("输入 q 退出: ")
    if choice == "q":
        break
    print(f"你输入了: {choice}")
def call_api():
    print("call_api")
    return False

# 重试直到成功
attempts = 0
max_attempts = 3
while attempts < max_attempts:
    ok = call_api()          # 假设返回是否成功
    if ok:
        break
    attempts += 1

5. while 与 for 怎么选 #

场景 推荐
遍历列表、字典、固定次数 for(更常见)
条件未知、直到满足才停 while
无限服务循环 + 内部 break while True
# 遍历用 for,不要用 while + index
for fruit in ["苹果", "香蕉"]:
    print(fruit)

6. 项目开发要点 #