还在纠结用while还是for?别怕!这篇文章手把手带你避开初学者最常见坑点,让你一次搞懂两种循环的本质区别。
嘿!又见面啦~我是你的 Python 学习搭子,跟你一样从零开始。
说到循环,相信你也经历过这种场景:在选择循环是用for还是while上面陷入纠结——while 和 for 有啥区别?什么时候用哪个?别急!今天我们就拿实际例子来拆解清楚,让你彻底告别选择困难!
前面我们已经学习了for循环,现在来看看它的兄弟——while循环。简单来说,while循环就是“只要条件满足,就一直重复做某件事”。
while 条件:# 循环体(要重复执行的代码块)# 从0数到7number = 0while number < 8: number += 1# 每次循环让number加1 print(f"当前数字:{number}")运行这个代码,你会看到:
当前数字:1当前数字:2...当前数字:8初学者最常犯的错误:忘记在循环体内更新条件变量。
# ❌ 错误示例:无限循环!number = 0while number < 8: print("我停不下来啦!") # 没有更新number,条件永远为True正确做法:确保循环体内有改变条件状态的操作。
# ✅ 正确示例:安全计数器number = 0while number < 8: number += 1# 关键!更新条件变量 print(f"安全计数:{number}")在实际应用中,我们经常需要根据用户输入来决定程序是否继续运行。
# 初始化继续标志is_continue = '是'while is_continue == '是' : answer = input("Python是一种编程语言吗?(是/不是): ").stripif answer == '是': print("太棒了!答对了!🎉")else: print("再想想哦~")# 询问用户是否继续 is_continue = input("是想继续玩吗?(是/不是): ").stripprint("游戏结束,下次再来玩!")❌ 错误示例:
answer = input("Python是一种编程语言吗?(是/不是): ")answer = input("...").strip()有时候我们需要在循环中“紧急刹车”或“跳过这一轮”。
# 密码输入尝试(最多3次)attempts = 0correct_password = "python123"while attempts < 3: password = input("请输入密码:")if password == correct_password: print("登录成功!🎊")break# 密码正确,立即跳出循环else : attempts += 1 print(f"密码错误,还剩{3 - attempts}次尝试机会")if attempts == 3: print("尝试次数过多,账户已锁定!")🎯 真实案例4:跳过本次循环的“小绕行”— continue语句
# 过滤列表中的负数numbers = [5, -2, 8, -1, 10, 3]positive_numbers = []index = 0while index < len(numbers):if numbers[index] < 0: print(f"跳过负数:{numbers[index]}") index += 1continue# 跳过负数,不加入列表 positive_numbers.append(numbers[index]) index += 1print(f"正数列表:{positive_numbers}") # 输出:[5, 8, 10, 3]# ❌ 错误示例:continue后忘记更新变量while index < len(numbers):if numbers[index] < 0:continue# 跳过后面的代码,但index没有增加!# ... 这会导致无限循环!# ✅ 正确示例:确保变量在continue前更新while index < len(numbers): current_num = numbers[index] index += 1# 先更新索引if current_num < 0:continue positive_numbers.append(current_num)这是初学者最困惑的问题!其实选择很简单!
| for循环 | |||
| while循环 |
# 学生名单students = ["张三", "李四", "王五", "赵六"]print("学生点名:")for student in students: print(f"{student}到!")# 如果用while实现(对比看看有多麻烦):print("\n用while实现同样的功能:")index = 0while index < len(students): print(f"{students[index]}到!") index += 1# ❌ 错误示例:用while遍历列表(自找麻烦)numbers = [1, 2, 3, 4, 5]i = 0while i < len(numbers): print(numbers[i]) i += 1# ✅ 正确示例:用for遍历(简洁明了)numbers = [1, 2, 3, 4, 5]for num in numbers: print(num)还在纠结?跟着这个决策树走:
需要循环吗? ├─ 需要遍历列表、字符串、字典等集合? │ └─ 用 for 循环(简洁安全) │ ├─ 循环次数不确定,只知道终止条件? │ ├─ 用户输入验证 → while │ ├─ 游戏主循环 → while │ └─ 条件满足就重复 → while │ └─ 两种都可以用? └─ 优先用 for(更简洁,更安全).strip()、.lower()或.upper()统一格式需求:创建一个登录系统,要求用户输入用户名和密码:
需求:编写一个程序,让用户输入数字,直到输入0为止:
我是你的Python学习搭子,每周都会分享这样的实战指南。如果你在while循环中遇到了其他坑,或者有想了解的主题,随时在评论区告诉我!
配套资源: