掌握Python中的条件循环结构
while循环是Python中的条件循环,只要条件为True,就会重复执行循环体中的代码。
while 条件表达式:
# 循环体代码
# 当条件为True时执行
# 需要更新条件,否则可能成为无限循环
# 简单的计数循环
count = 1
while count <= 5:
print(f"这是第{count}次循环")
count += 1 # 更新计数器
print("循环结束!")
# 输出结果:
# 这是第1次循环
# 这是第2次循环
# 这是第3次循环
# 这是第4次循环
# 这是第5次循环
# 循环结束!
理解while循环和for循环的区别,选择合适的情况使用。
| 特性 | While循环 | For循环 |
|---|---|---|
| 使用场景 | 不确定循环次数时 | 确定循环次数时 |
| 控制方式 | 条件控制 | 序列控制 |
| 语法 | while 条件: | for 变量 in 序列: |
| 无限循环风险 | 有(需手动更新条件) | 无(自动结束) |
| 适用数据结构 | 不限制 | 可迭代对象 |
# 目标:计算1到10的和
# 使用while循环实现
total1 = 0
i = 1
while i <= 10:
total1 += i
i += 1
print(f"while循环结果: {total1}")
# 使用for循环实现
total2 = 0
for i in range(1, 11):
total2 += i
print(f"for循环结果: {total2}")
# 输出结果:
# while循环结果: 55
# for循环结果: 55
Python提供了break、continue和pass语句来控制循环的流程。
# break示例:在数字7时终止循环
number = 1
while number <= 10:
if number == 7:
print("找到数字7,终止循环!")
break
print(f"当前数字: {number}")
number += 1
print("循环结束")
# 输出结果:
# 当前数字: 1
# 当前数字: 2
# 当前数字: 3
# 当前数字: 4
# 当前数字: 5
# 当前数字: 6
# 找到数字7,终止循环!
# 循环结束
# continue示例:跳过奇数,只打印偶数
number = 0
while number < 10:
number += 1
if number % 2 == 1: # 如果是奇数
continue # 跳过本次循环的剩余部分
print(f"偶数: {number}")
# 输出结果:
# 偶数: 2
# 偶数: 4
# 偶数: 6
# 偶数: 8
# 偶数: 10
# while-else结构
count = 1
while count <= 5:
print(f"执行第{count}次")
count += 1
else:
print("循环正常结束,没有遇到break")
# 输出结果:
# 执行第1次
# 执行第2次
# 执行第3次
# 执行第4次
# 执行第5次
# 循环正常结束,没有遇到break
while循环很容易创建无限循环,但有时这也是我们需要的(如游戏主循环)。
# 危险示例:这将导致无限循环!
# count = 1
# while count <= 5:
# print("循环中...")
# # 忘记更新 count,条件永远为True
# # 程序将永远运行,需要强制终止
# 安全示例:有退出条件的循环
counter = 0
while True: # 条件永远为True
print(f"循环次数: {counter + 1}")
counter += 1
if counter >= 5: # 设置退出条件
print("达到退出条件,结束循环")
break
# 猜数字游戏
import random
secret_number = random.randint(1, 100)
attempts = 0
max_attempts = 10
print("欢迎来到猜数字游戏!")
print("我已经想好了一个1到100之间的数字。")
while attempts < max_attempts:
try:
guess = int(input(f"第{attempts + 1}次尝试,请输入你的猜测: "))
if guess < secret_number:
print("太小了!")
elif guess > secret_number:
print("太大了!")
else:
print(f"恭喜!你猜对了!数字是{secret_number}")
print(f"你用了{attempts + 1}次尝试")
break
attempts += 1
except ValueError:
print("请输入有效的数字!")
if attempts >= max_attempts:
print(f"很遗憾,你没有猜对。正确答案是{secret_number}")
print("游戏结束!")
在while循环内部可以再放置while循环,用于处理复杂逻辑。
# 使用嵌套while循环打印乘法表
print("九九乘法表:")
i = 1
while i <= 9: # 外层循环,控制行
j = 1
while j <= i: # 内层循环,控制列
result = i * j
print(f"{j}×{i}={result:2d}", end=" ")
j += 1
print() # 换行
i += 1
# 输出结果:
# 1×1= 1
# 1×2= 2 2×2= 4
# 1×3= 3 2×3= 6 3×3= 9
# ...
# 简单菜单系统
while True: # 主循环
print("\n=== 菜单系统 ===")
print("1. 选项一")
print("2. 选项二")
print("3. 退出")
choice = input("请选择(1-3): ")
if choice == "1":
# 子菜单
while True:
print("\n--- 子菜单一 ---")
print("a. 功能A")
print("b. 功能B")
print("c. 返回主菜单")
sub_choice = input("请选择(a-c): ")
if sub_choice == "a":
print("执行功能A...")
elif sub_choice == "b":
print("执行功能B...")
elif sub_choice == "c":
print("返回主菜单...")
break
else:
print("无效选择,请重试")
elif choice == "2":
print("执行选项二...")
elif choice == "3":
print("谢谢使用,再见!")
break
else:
print("无效选择,请重试")
将while循环应用于实际场景,解决实际问题。
# 密码验证系统
correct_password = "python123"
max_attempts = 3
attempts = 0
while attempts < max_attempts:
password = input("请输入密码: ")
if password == correct_password:
print("密码正确!登录成功!")
break
else:
attempts += 1
remaining_attempts = max_attempts - attempts
if remaining_attempts > 0:
print(f"密码错误!还有{remaining_attempts}次尝试机会")
else:
print("密码错误!账户已被锁定")
else:
print("您已尝试3次,账户暂时锁定,请30分钟后再试")
# 简单计算器程序
print("简单计算器")
print("输入 'q' 退出程序")
while True:
# 获取第一个数字
num1 = input("请输入第一个数字: ")
if num1.lower() == 'q':
print("感谢使用计算器!")
break
# 获取运算符
operator = input("请选择运算符 (+, -, *, /): ")
if operator.lower() == 'q':
print("感谢使用计算器!")
break
# 获取第二个数字
num2 = input("请输入第二个数字: ")
if num2.lower() == 'q':
print("感谢使用计算器!")
break
try:
# 转换类型
num1 = float(num1)
num2 = float(num2)
# 计算结果
if operator == '+':
result = num1 + num2
elif operator == '-':
result = num1 - num2
elif operator == '*':
result = num1 * num2
elif operator == '/':
if num2 == 0:
print("错误:除数不能为0!")
continue
result = num1 / num2
else:
print("错误:无效的运算符!")
continue
print(f"结果: {num1} {operator} {num2} = {result}")
except ValueError:
print("错误:请输入有效的数字!")
except Exception as e:
print(f"发生错误: {e}")
print("-" * 30) # 分隔线