今天,我们将探索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跳过迭代
- 真实世界示例,如登录验证和猜谜游戏