当前位置:首页>python>Python 零基础 100 天 — Day 7 while 循环

Python 零基础 100 天 — Day 7 while 循环

  • 2026-10-11 08:04:29
Python 零基础 100 天 — Day 7 while 循环

🐍 循环进阶 — while 循环

🕐 预计用时:2-3 小时 | 🎯 今日目标:掌握 while 循环,处理"不知道要循环几次"的场景


📖 今日目录

  1. while vs for:什么时候用哪个?
  2. while 循环基本语法
  3. while True + break:无限循环
  4. while + continue
  5. while/else
  6. 常见陷阱:死循环
  7. 实战项目
  8. 今日小结

1. while vs for:什么时候用哪个?

上节课学了 for 循环,这节课学 while 循环。它们都能做重复的事,但适用场景不同:

对比
for 循环
while 循环
适合场景
已知要循环多少次
不知道要循环多少次
典型用法
遍历列表、range(n)
条件满足就继续
生活比喻
流水线:100件产品逐个检查
等公交:不知道什么时候来,来了才走
例子
打印1到100
猜数字游戏(猜对才停)

💡 简单判断法: 如果你能提前说出"循环几次",用 for。 如果你只能说"直到某个条件",用 while。


2. while 循环基本语法

📐 语法结构

while 条件:    循环体(条件为 True 就一直执行)

执行流程:判断条件 → True就执行循环体 → 回到判断条件 → True再执行 → ... → 直到条件为False → 结束

🎯 最简单的例子

# 打印 1 到 5count = 1while count <= 5:    print(count)    count += 1    # 别忘了更新条件!否则死循环

输出:

12345

🔍 逐步拆解执行过程

第1轮:count=1 → 1<=5 True → print(1) → count=2第2轮:count=2 → 2<=5 True → print(2) → count=3第3轮:count=3 → 3<=5 True → print(3) → count=4第4轮:count=4 → 4<=5 True → print(4) → count=5第5轮:count=5 → 5<=5 True → print(5) → count=6第6轮:count=6 → 6<=5 False → 循环结束!

⚠️ while 循环的三大要素(缺一不可): 1. 初始化:循环前设置好变量的初始值 2. 条件:决定什么时候继续、什么时候停 3. 更新:每次循环都要改变变量,否则永远不满足退出条件 → 死循环!

# ❌ 忘记更新 → 死循环!count = 1while count <= 5:    print(count)    # 忘了 count += 1,永远打印 1...# ✅ 正确写法count = 1while count <= 5:    print(count)    count += 1    # 每次 +1,最终会超过 5

🔢 while 实现累加

# 计算 1+2+3+...+100total = 0i = 1while i <= 100:    total += i    i += 1print("1到100的和 =", total)  # 5050

3. while True + break:无限循环

有时候我们希望循环"一直运行,直到某个条件才退出"。这时候用 while True。

while True:    # 永远为 True,不会自己停    代码块    if 退出条件:        break  # 满足条件才跳出

🎯 猜数字游戏(简化版)

secret = 42while True:    guess = int(input("猜一个数字:"))    if guess == secret:        print("🎉 恭喜,猜对了!")        break    # 猜对了就跳出    elif guess < secret:        print("太小了!")    else:        print("太大了!")

运行效果:

猜一个数字:50太大了!猜一个数字:25太小了!猜一个数字:42🎉 恭喜,猜对了!

💡 while True 的理解方式:while True = "我不管条件了,反正一直跑" break = "但是遇到这种情况,我就不跑了" 就像你在餐厅等朋友——你不知道他什么时候来(循环次数未知),但你看到他了就站起来走(break)。

📋 菜单循环(实用例子)

while True:    print("\n=== 菜单 ===")    print("1. 查看余额")    print("2. 存钱")    print("3. 取钱")    print("0. 退出")    choice = input("请选择:")    if choice == "1":        print("余额:1000元")    elif choice == "2":        amount = float(input("存多少?"))        print("存入", amount, "元成功")    elif choice == "3":        amount = float(input("取多少?"))        print("取出", amount, "元成功")    elif choice == "0":        print("再见!")        break    else:        print("无效选择,请重试")

4. while + continue

continue 跳过本次循环,回到 while 条件判断。

# 打印 1~10 中的奇数i = 0while i < 10:    i += 1    if i % 2 == 0:        continue    # 偶数跳过    print(i)

输出:

13579

⚠️ continue 的坑: 在 while 循环中,continue 会跳回循环开头。如果更新变量的代码在 continue 之后,可能不会被执行,导致死循环!

# ❌ 死循环!i = 0while i < 10:    i += 1    if i % 2 == 0:        continue    # 跳回开头,i 没变    print(i)# 上面的代码其实是OK的,因为 i += 1 在 continue 之前# ❌ 真正的死循环:i = 0while i < 10:    if i % 2 == 0:        continue    # i 永远是 0,永远 True    i += 1          # 这行永远不会执行

5. while/else

和 for/else 类似:循环正常结束(没有 break)时执行 else。

# 找第一个能被 7 整除的数numbers = [1, 3, 5, 8, 9, 14, 20]i = 0while i < len(numbers):    if numbers[i] % 7 == 0:        print("找到了:", numbers[i])        break    i += 1else:    print("没找到能被7整除的数")

输出:找到了: 14(不会执行 else)


6. 常见陷阱:死循环

死循环 = 条件永远为 True,循环永远停不下来。

错误类型
代码
原因
忘记更新
while x < 5: print(x)
x 永远不变
更新方向错
while x > 0: x += 1
x 越来越大,永远大于0
条件写错
while x != 10: x += 2
如果 x 从奇数开始,永远不等于10

💡 遇到死循环怎么办? 按 Ctrl + C 强制终止程序。 或者在 VS Code 中点击终端 → 垃圾桶图标终止。


7. 实战项目

🏋️ 实战 1:猜数字游戏(完整版)

import randomprint("=== 猜数字游戏 ===")print("规则:1~100之间选一个数,最多猜7次")secret = random.randint(1, 100)attempts = 0max_attempts = 7while attempts < max_attempts:    attempts += 1    guess = int(input(f"\n第{attempts}/{max_attempts}次猜测:"))    if guess == secret:        print(f"🎉 恭喜!答案就是 {secret}!")        print(f"你用了 {attempts} 次猜中")        break    elif guess < secret:        print("太小了 ↑")    else:        print("太大了 ↓")else:    print(f"\n💀 机会用完了!答案是 {secret}")

🏋️ 实战 2:简易 ATM

balance = 1000.0print("=== 欢迎使用 Python ATM ===")while True:    print(f"\n当前余额:{balance}元")    print("1. 查询余额")    print("2. 存款")    print("3. 取款")    print("0. 退出")    choice = input("请选择操作:")    if choice == "1":        print(f"您的余额是:{balance}元")    elif choice == "2":        amount = float(input("请输入存款金额:"))        if amount > 0:            balance += amount            print(f"存款成功!存入 {amount} 元")        else:            print("金额必须大于0!")    elif choice == "3":        amount = float(input("请输入取款金额:"))        if amount > balance:            print("余额不足!")        elif amount <= 0:            print("金额必须大于0!")        else:            balance -= amount            print(f"取款成功!取出 {amount} 元")    elif choice == "0":        print("感谢使用,再见!")        break    else:        print("无效选择,请重试")

🏋️ 实战 3:密码验证器

correct_password = "python123"max_tries = 3tries = 0print("=== 登录系统 ===")while tries < max_tries:    password = input("请输入密码:")    tries += 1    if password == correct_password:        print("✅ 登录成功!")        break    else:        remaining = max_tries - tries        if remaining > 0:            print(f"❌ 密码错误!还剩 {remaining} 次机会")        else:            print("🔒 账号已锁定!请稍后再试")

🏋️ 练习题

练习 1:用 while 循环计算 1×2×3×...×10 的乘积(阶乘)。

练习 2:写一个程序,让用户不断输入数字,输入 "quit" 时退出,最后输出所有数字的平均值。

练习 3:用 while 循环反转一个数字。例如输入 12345,输出 54321。(提示:用 % 取末位,用 // 去掉末位)

练习 4:写一个"石头剪刀布"游戏,玩家 vs 电脑,先赢3局者获胜。


8. 今日小结

知识点
一句话总结
while 循环
条件为 True 就一直执行,适合"不知道循环几次"的场景
while True
无限循环,必须配合 break 使用
break
跳出整个 while 循环
continue
跳过本次,回到 while 条件判断
while/else
循环正常结束(无 break)时执行 else
死循环
条件永远为 True,用 Ctrl+C 终止
while 三大要素
初始化、条件、更新——缺一不可

🧠 自检清单

⬜ 能用 while 循环实现累加/累乘

⬜ 能用 while True + break 实现菜单循环

⬜ 知道 continue 在 while 中的风险

⬜ 能写一个猜数字游戏

⬜ 能写一个简易 ATM 程序

⬜ 知道死循环的原因和解决方法

🎯 Day 8 预告

明天学习列表(List)——Python 最常用的数据结构,可以存储一组有序的数据。

就像一个"超级收纳盒",能装任何东西!📦


📅 Day 7 完成!你已经掌握了 while 循环。for + while 双剑合璧,循环这块基本毕业了!明天见! 🚀

轻松时刻:

最新文章

随机文章