网站首页 > 技术文章 正文
今天,我们将探索while循环的力量 — 这是一个帮助您的程序重复**执行操作直到某个条件不再为真的工具。
您还将看到while循环在真实世界应用中的使用,从输入验证到简单游戏。
您将学习什么
- 什么是while循环
- 如何使用条件控制重复
- 使用break和continue
- 真实世界示例:密码检查、倒计时、数字猜谜游戏
什么是while循环?
while循环**只要条件为True**就重复执行代码块。
语法:
while condition:
# 做某事
基本示例
count = 1
while count <= 5:
print("Count:", count)
count += 1
输出:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
一旦count变成6,循环条件count <= 5就不再为真,所以循环停止。
避免无限循环
确保您的循环条件最终会变为false — 否则您将创建一个无限循环:
# 这将永远运行,除非您停止它
while True:
print("This goes on and on...")
使用break退出循环
您可以使用break强制退出循环。
while True:
answer = input("Type 'exit' to stransform: translateY( ")
if answer == 'exit':
print("Goodbye!")
break
使用continue跳过迭代
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("Enter password: ")
if password == correct_password:
print("Access granted.")
break
else:
print("Wrong password.")
attempts += 1
if attempts == 3:
print("Too many attempts. Access denied.")
真实世界示例2:倒计时定时器
import time
countdown = 5
while countdown > 0:
print(countdown)
time.sleep(1) # 暂停1秒
countdown -= 1
print("Time's up!")
真实世界示例3:数字猜谜游戏
import random
number = random.randint(1, 10)
guess = 0
while guess != number:
guess = int(input("Guess a number between 1 and 10: "))
if guess < number:
print("Too low!")
elif guess > number:
print("Too high!")
else:
print("Correct!")
回顾
今天您学习了:
- 如何使用while循环重复任务
- 如何使用break提前停止循环
- 如何使用continue跳过迭代
- 真实世界示例,如登录验证和猜谜游戏
猜你喜欢
- 2025-07-27 UV 迄今最快、最好的 Python 包管理器
- 2025-07-27 Python“三步”即可爬取,毋庸置疑
- 2025-07-27 第二章:Python 运算符与表达式(python语言中运算符号)
- 2025-07-27 掌握Python比较运算符:核心要点与实战解析
- 2025-07-27 Python开发必会技巧:访问限制(python访问数据)
- 2025-07-27 Python字符串对齐神技!4种方法让你的输出瞬间专业10倍
- 2025-07-27 Python运算符与表达式(python运算符含义)
- 2025-07-27 一图看懂 Python 2 / Python 3 编码 | CSDN 博文精选
- 2025-07-27 让 Python 代码飙升330倍:从入门到精通的四种性能优化实践
- 2025-05-03 如何在 Python 中创建一个不可变的字典 - Adam Johnson
- 最近发表
- 标签列表
-
- cmd/c (90)
- c++中::是什么意思 (84)
- 标签用于 (71)
- 主键只能有一个吗 (77)
- c#console.writeline不显示 (95)
- pythoncase语句 (88)
- es6includes (74)
- sqlset (76)
- apt-getinstall-y (100)
- node_modules怎么生成 (87)
- chromepost (71)
- flexdirection (73)
- c++int转char (80)
- mysqlany_value (79)
- static函数和普通函数 (84)
- el-date-picker开始日期早于结束日期 (76)
- js判断是否是json字符串 (75)
- asynccallback (71)
- localstorage.removeitem (74)
- vector线程安全吗 (70)
- java (73)
- js数组插入 (83)
- mac安装java (72)
- 查看mysql是否启动 (70)
- 无效的列索引 (74)