重复劳动交给电脑!

你有没有过这样的经历:

  • 要给1000个文件重命名,一个一个改到吐血
  • 要从100个Excel表格里提取数据,复制粘贴到天荒地老
  • 要给1000个人发邮件,手动发到崩溃

别再假装你会手动完成这些事了,交给Python吧!

循环就是让电脑重复做某件事,一次做1000次、10000次,几秒钟搞定。

for循环:遍历一个序列

基本语法

for 变量 in 序列:
    # 重复执行的代码
    pass

遍历列表

names = ["小明", "小红", "小刚", "小李"]

for name in names:
    print("你好," + name + "!")

运行结果:

你好,小明!
你好,小红!
你好,小刚!
你好,小李!

遍历字符串

word = "Python"

for letter in word:
    print(letter)

运行结果:

P
y
t
h
o
n

range()函数:生成数字序列

# range(5)生成0, 1, 2, 3, 4
for i in range(5):
    print(i)

运行结果:

0
1
2
3
4

注意: range(5)是从0开始,到4结束(不包含5)!

# range(1, 6)生成1, 2, 3, 4, 5
for i in range(1, 6):
    print(i)

# range(1, 10, 2)生成1, 3, 5, 7, 9(步长为2)
for i in range(1, 10, 2):
    print(i)

while循环:条件满足就一直循环

基本语法

while 条件:
    # 条件成立时重复执行的代码
    pass

简单例子

count = 0

while count < 5:
    print("现在是第" + str(count + 1) + "次")
    count = count + 1  # 或者写成 count += 1

运行结果:

现在是第1次
现在是第2次
现在是第3次
现在是第4次
现在是第5次

一定要有退出条件!

count = 0

while count < 5:
    print("循环中...")
    # count += 1  # 如果注释掉这行,会无限循环!

无限循环就像停不下来的跑步机,电脑会卡死!

break和continue:控制循环

break:跳出循环

for i in range(10):
    if i == 5:
        break  # 到5就跳出循环
    print(i)

运行结果:

0
1
2
3
4

continue:跳过本次循环

for i in range(10):
    if i % 2 == 0:  # 偶数就跳过
        continue
    print(i)

运行结果:

1
3
5
7
9

for循环和while循环的区别

场景 推荐使用 原因
遍历列表、字符串 for循环 代码更简洁
执行固定次数的循环 for循环 + range() 不用自己计数
不确定循环次数 while循环 灵活
等待某个条件满足 while循环 可以随时退出

实战小项目1:计算1到100的和

# 方法1:for循环
total = 0
for i in range(1, 101):
    total += i
print("1到100的和是:" + str(total))

# 方法2:while循环
total = 0
i = 1
while i <= 100:
    total += i
    i += 1
print("1到100的和是:" + str(total))

运行结果:

1到100的和是:5050

实战小项目2:打印乘法口诀表

for i in range(1, 10):
    for j in range(1, i + 1):
        print(f"{j} x {i} = {i*j}", end="\t")
    print()  # 换行

运行结果:

1 x 1 = 1
1 x 2 = 2	2 x 2 = 4
1 x 3 = 3	2 x 3 = 6	3 x 3 = 9
1 x 4 = 4	2 x 4 = 8	3 x 4 = 12	4 x 4 = 16
1 x 5 = 5	2 x 5 = 10	3 x 5 = 15	4 x 5 = 20	5 x 5 = 25
1 x 6 = 6	2 x 6 = 12	3 x 6 = 18	4 x 6 = 24	5 x 6 = 30	6 x 6 = 36
1 x 7 = 7	2 x 7 = 14	3 x 7 = 21	4 x 7 = 28	5 x 7 = 35	6 x 7 = 42	7 x 7 = 49
1 x 8 = 8	2 x 8 = 16	3 x 8 = 24	4 x 8 = 32	5 x 8 = 40	6 x 8 = 48	7 x 8 = 56	8 x 8 = 64
1 x 9 = 9	2 x 9 = 18	3 x 9 = 27	4 x 9 = 36	5 x 9 = 45	6 x 9 = 54	7 x 9 = 63	8 x 9 = 72	9 x 9 = 81

实战小项目3:批量重命名文件

import os

# 假设你有一个文件夹里有10个文件,想给它们按顺序重命名
folder_path = "./test_files"  # 改成你的文件夹路径

# 创建测试文件
for i in range(1, 11):
    with open(f"{folder_path}/file_{i}.txt", "w") as f:
        f.write(f"这是第{i}个文件")

# 批量重命名
files = os.listdir(folder_path)
count = 1

for filename in files:
    old_path = os.path.join(folder_path, filename)
    new_name = f"文件_{count}.txt"
    new_path = os.path.join(folder_path, new_name)

    os.rename(old_path, new_path)
    print(f"将 {filename} 重命名为 {new_name}")
    count += 1

print("重命名完成!")

实战小项目4:猜数字游戏(优化版)

import random

secret = random.randint(1, 100)
max_attempts = 10  # 最多猜10次
attempts = 0

print("我已经想好了一个1-100的数字,你有10次机会猜!")

while attempts < max_attempts:
    guess = int(input("请输入你的猜测(剩下" + str(max_attempts - attempts) + "次机会):"))
    attempts += 1

    if guess < secret:
        print("太小了!")
    elif guess > secret:
        print("太大了!")
    else:
        print(f"恭喜你猜对了!数字就是{secret},你用了{attempts}次!")
        break
else:
    print(f"游戏结束!正确答案是{secret}")

常见坑及解决方案

坑1:忘记更新循环变量

count = 0
while count < 5:
    print(count)
    # 忘记 count += 1,会无限循环

解决: while循环一定要有退出条件!

坑2:range()的右边界不包含

for i in range(5):
    print(i)  # 输出0, 1, 2, 3, 4,不包括5

记住: range(n)是从0到n-1!

址3:嵌套循环的效率问题

# 三层嵌套循环,效率很低
for i in range(100):
    for j in range(100):
        for k in range(100):
            pass  # 执行100万次

解决: 尽量减少嵌套层数,考虑用其他方式优化。

本章小结

  • for循环:遍历列表、字符串,配合range()执行固定次数循环
  • while循环:不确定循环次数时使用,一定要有退出条件
  • break:跳出循环
  • continue:跳过本次循环
  • 嵌套循环:循环里再套循环,注意效率问题

循环让电脑能一次做1000件事,但如果每次都要重复写代码,那就太麻烦了。下一章我们学习函数,把代码打包成工具,一次写好,重复使用!

继续学下去,马上就能做实用项目了!