苦练Python第8天:while 循环之妙用

苦练Python第8天:while 循环之妙用

原文链接:https://dev.to/therahul_gupta/day-9100-while-loops-with-real-world-examples-528f
作者:Rahul Gupta
译者:倔强青铜三

前言

大家好,我是倔强青铜三。是一名热情的软件工程师,我热衷于分享和传播IT技术,致力于通过我的知识和技能推动技术交流与创新,欢迎关注我,微信公众号:倔强青铜三。欢迎点赞、收藏、关注,一键三连!!!

欢迎来到 100天Python挑战 第8天!
今天带你掌握 while 循环:让程序重复干活直到天荒地老,还能优雅地喊停、跳过、验证密码、倒计时、猜数字,全部实战演示。


今日速览

  • while 循环语法与运行逻辑
  • 避开无限循环的坑
  • breakcontinue 精准控制
  • 三大实战:密码验证、倒计时、猜数字游戏

什么是 while 循环?

只要条件为 True,就重复执行代码块:

while 条件:
    # 循环体

✅ 基础示范

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

输出:

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

count 变成 6,条件不再成立,循环结束。


别掉进无限循环

忘记更新变量就会死循环:

# ⚠️ 请勿运行
while True:
    print("停不下来...")

务必让条件终有 False 的一天。


break 强制逃生

立即终止整个循环:

while True:
    answer = input("输入 exit 退出: ")
    if answer == 'exit':
        print("Goodbye!")
        break

⏭️ continue 跳过本轮

直接进入下一轮迭代:

x = 0
while x < 5:
    x += 1
    if x == 3:
        continue
    print(x)

输出:

1
2
4
5

数字 3 被跳过。


实战 1:密码验证器

correct_password = "python123"
attempts = 0

while attempts < 3:
    password = input("请输入密码: ")
    if password == correct_password:
        print("验证通过")
        break
    else:
        print("密码错误")
        attempts += 1

if attempts == 3:
    print("尝试过多,禁止访问")

⏳ 实战 2:倒计时器

import time

countdown = 5
while countdown > 0:
    print(countdown)
    time.sleep(1)
    countdown -= 1

print("时间到!")

实战 3:猜数字小游戏

import random

number = random.randint(1, 10)
guess = 0

while guess != number:
    guess = int(input("猜 1~10 之间的整数: "))
    if guess < number:
        print("太小!")
    elif guess > number:
        print("太大!")
    else:
        print("猜中啦!")

今日复盘

  • while 让代码重复跑
  • break 提前收工
  • continue 跳过回合
  • 把循环搬进密码、倒计时、游戏的真实场景
最后感谢阅读!欢迎关注我,微信公众号倔强青铜三。欢迎点赞收藏关注,一键三连!!!

你可能感兴趣的:(python后端前端人工智能)