Python案例怎么实现循环?

wen python案例 17

本文目录导读:

Python案例怎么实现循环?

  1. for循环 - 最常用的循环
  2. while循环 - 条件控制
  3. 嵌套循环
  4. 循环控制语句
  5. 实用案例
  6. 循环技巧

我来详细介绍Python中实现循环的各种方法,包括实际案例。

for循环 - 最常用的循环

遍历列表

# 案例:遍历学生名单
students = ['Alice', 'Bob', 'Charlie', 'David']
for student in students:
    print(f"学生: {student}")
# 输出:
# 学生: Alice
# 学生: Bob
# 学生: Charlie
# 学生: David

遍历数字范围

# 案例:打印1-10的平方
for i in range(1, 11):
    square = i ** 2
    print(f"{i}的平方是:{square}")

遍历字典

# 案例:统计商品库存
inventory = {
    '苹果': 50,
    '香蕉': 30,
    '橙子': 40
}
# 遍历键值对
for item, quantity in inventory.items():
    print(f"{item}: {quantity}个")

while循环 - 条件控制

基础用法

# 案例:倒计时
count = 5
while count > 0:
    print(f"倒计时: {count}")
    count -= 1
print("开始!")
# 输出:
# 倒计时: 5
# 倒计时: 4
# 倒计时: 3
# 倒计时: 2
# 倒计时: 1
# 开始!

用户输入验证

# 案例:密码验证(最多尝试3次)
password = "python123"
attempts = 3
while attempts > 0:
    user_input = input("请输入密码: ")
    if user_input == password:
        print("登录成功!")
        break
    else:
        attempts -= 1
        if attempts > 0:
            print(f"密码错误,还剩{attempts}次机会")
        else:
            print("登录失败,账户已锁定")

嵌套循环

打印乘法表

# 案例:打印9x9乘法表
for i in range(1, 10):
    for j in range(1, i + 1):
        print(f"{j}x{i}={i*j:2d}", end=" ")
    print()  # 换行

二维列表遍历

# 案例:学生成绩表
grades = [
    [85, 92, 78],
    [90, 88, 95],
    [76, 85, 89]
]
for row in range(len(grades)):
    total = 0
    for col in range(len(grades[row])):
        total += grades[row][col]
        print(f"第{row+1}行第{col+1}列: {grades[row][col]}")
    average = total / len(grades[row])
    print(f"第{row+1}行平均分: {average:.2f}")
    print("-" * 30)

循环控制语句

break语句

# 案例:查找第一个偶数
numbers = [1, 3, 5, 6, 7, 9, 10]
for num in numbers:
    if num % 2 == 0:
        print(f"找到第一个偶数: {num}")
        break   # 找到后立即退出循环

continue语句

# 案例:只打印奇数
for num in range(1, 11):
    if num % 2 == 0:
        continue  # 跳过偶数
    print(f"奇数: {num}")

else子句

# 案例:检查列表中是否有偶数
numbers = [1, 3, 5, 7, 9]
for num in numbers:
    if num % 2 == 0:
        print("找到偶数")
        break
else:
    print("没有找到偶数")  # 循环正常结束时执行

实用案例

猜数字游戏

import random
# 案例:猜数字游戏
target = random.randint(1, 100)
attempts = 0
print("猜数字游戏(1-100)")
while True:
    guess = int(input("请输入你的猜测: "))
    attempts += 1
    if guess < target:
        print("猜小了")
    elif guess > target:
        print("猜大了")
    else:
        print(f"恭喜你猜对了!共猜了{attempts}次")
        break

斐波那契数列

# 案例:生成斐波那契数列
def fibonacci(n):
    a, b = 0, 1
    result = []
    for _ in range(n):
        result.append(a)
        a, b = b, a + b
    return result
# 生成前10个斐波那契数
fib_numbers = fibonacci(10)
print("斐波那契数列:", fib_numbers)

购物车计算

# 案例:购物车结算
shopping_cart = [
    {"name": "苹果", "price": 5.5, "quantity": 2},
    {"name": "香蕉", "price": 3.0, "quantity": 3},
    {"name": "牛奶", "price": 12.0, "quantity": 1}
]
total = 0
print("购物清单:")
for item in shopping_cart:
    subtotal = item["price"] * item["quantity"]
    total += subtotal
    print(f"{item['name']} x{item['quantity']} = ¥{subtotal:.2f}")
print(f"总计: ¥{total:.2f}")

循环技巧

使用enumerate获取索引

# 案例:显示列表索引和值
fruits = ['苹果', '香蕉', '橙子', '葡萄']
for index, fruit in enumerate(fruits):
    print(f"索引{index}: {fruit}")

使用zip并行遍历

# 案例:配对两个列表
names = ['Alice', 'Bob', 'Charlie']
scores = [85, 92, 78]
for name, score in zip(names, scores):
    print(f"{name}: {score}分")

这些是Python中实现循环的常见方式,根据不同的场景选择合适的循环结构可以提高代码的效率和可读性。

抱歉,评论功能暂时关闭!