Python 循环结构实战:从基础语法到自动化脚本
📅 2026/7/16 23:47:14
👁️ 阅读次数
📝 编程学习
1. Python循环结构基础:while与for的实战入门
第一次接触Python循环时,我被那个自动打印100份报表的脚本震惊了——原来3行代码就能完成我整天的工作。循环结构就像编程世界的"复制粘贴"神器,但比Ctrl+C/V智能得多。
1.1 while循环:当条件成立时持续行动
while循环就像固执的监工,只要条件满足就会一直干活。先看这个生产线监控案例:
power_on = True production_count = 0 while power_on: production_count += 1 print(f"正在加工第{production_count}个零件") if production_count >= 100: power_on = False elif random.random() < 0.01: # 模拟1%的停电概率 print("警告:突发停电!") break print(f"今日完成产量:{production_count}个")这里有两个重点:
- 循环条件管理:通过修改power_on变量控制循环
- 紧急中断机制:用break应对突发情况
实际项目中,我常用while循环处理:
- 实时数据监控(如股票价格波动)
- 服务状态检查(直到服务恢复正常)
- 用户输入验证(反复提示直到输入合法)
1.2 for循环:精确遍历已知序列
for循环则是严谨的会计,按清单逐个清点。对比下面两种写法:
# 传统写法 fruits = ["苹果", "香蕉", "橙子"] index = 0 while index < len(fruits): print(fruits[index]) index += 1 # Pythonic写法 for fruit in fruits: print(fruit)for循环的优势在于:
- 自动处理索引边界
- 代码可读性更强
- 支持直接遍历字符串/字典等数据结构
我处理Excel数据时最常用的模式:
import openpyxl workbook = openpyxl.load_workbook("销售数据.xlsx") sheet = workbook.active for row in sheet.iter_rows(values_only=True): product, sales = row[0], row[1] if sales > 1000: print(f"{product}销量超标:{sales}件")2. 循环控制语句:break与continue的妙用
调试第一个自动化脚本时,我因为忘记加break导致发了1000封测试邮件...现在这些经验都成了我的避坑指南。
2.1 break:紧急停止的红色按钮
break就像循环的紧急制动,典型应用场景包括:
- 搜索命中即停止:
database = ["A1", "B2", "C3", "目标数据", "D4"] found = False for item in database: if item == "目标数据": found = True print("数据已找到!") break if not found: print("数据不存在")- 异常熔断机制:
max_retry = 3 attempt = 0 while attempt < max_retry: try: response = requests.get("https://api.example.com") break # 请求成功则跳出循环 except Exception as e: print(f"第{attempt+1}次尝试失败:{str(e)}") attempt += 12.2 continue:跳过当前项的智能过滤器
continue则是精致的跳过机制,我的日志清洗脚本就靠它:
raw_logs = [ "INFO: 系统启动", "DEBUG: 内存分配", "ERROR: 文件丢失", "TRACE: 函数调用", "ERROR: 网络超时" ] error_logs = [] for log in raw_logs: if not log.startswith("ERROR"): continue # 跳过非错误日志 error_logs.append(log.split(":")[1].strip()) print("关键错误:", error_logs)实际项目中的continue使用技巧:
- 过滤无效数据(如None或空字符串)
- 跳过特定类型文件(如临时文件)
- 处理异常值时保持循环继续
3. 循环进阶:嵌套与迭代器实战
当第一次用嵌套循环处理财务报表时,我真正理解了什么叫"降维打击"——原本需要手动操作几小时的工作,现在10秒搞定。
3.1 嵌套循环:多维数据处理利器
典型的多层目录文件处理:
import os base_dir = "项目文档" target_extension = ".pdf" for root, dirs, files in os.walk(base_dir): for filename in files: if filename.endswith(target_extension): filepath = os.path.join(root, filename) print(f"找到PDF文档:{filepath}") # 这里可以添加PDF处理逻辑嵌套循环的性能优化建议:
- 尽量减少内层循环的计算量
- 使用生成器替代大列表
- 考虑是否能用笛卡尔积替代:
from itertools import product colors = ["红", "蓝"] sizes = ["S", "M", "L"] for color, size in product(colors, sizes): print(f"{color}色 {size}码")3.2 迭代器:处理海量数据的秘诀
当处理10GB日志文件时,直接读取内存会崩溃。这时就需要迭代器:
class BigFileReader: def __init__(self, filepath): self.filepath = filepath def __iter__(self): with open(self.filepath, "r", encoding="utf-8") as f: for line in f: yield line.strip() reader = BigFileReader("超大日志.log") for line in reader: if "ERROR" in line: process_error(line) # 逐行处理而不耗尽内存我常用的迭代器模式还包括:
- 数据库游标分批获取
- 流式API数据处理
- 无限序列生成(如斐波那契数列)
4. 自动化脚本实战案例
去年我用Python循环改造了公司的周报系统,把团队平均工时从4小时降到15分钟。以下是几个经典场景的实现。
4.1 文件批量处理系统
import os import shutil from datetime import datetime def organize_files(source_dir, target_dir): """按扩展名分类文件""" if not os.path.exists(target_dir): os.makedirs(target_dir) for filename in os.listdir(source_dir): source_path = os.path.join(source_dir, filename) if os.path.isdir(source_path): continue ext = filename.split(".")[-1].lower() ext_dir = os.path.join(target_dir, ext) if not os.path.exists(ext_dir): os.mkdir(ext_dir) timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") new_name = f"{timestamp}_{filename}" target_path = os.path.join(ext_dir, new_name) shutil.move(source_path, target_path) print(f"移动 {filename} 到 {ext}目录") organize_files("下载文件夹", "整理后的文件")4.2 数据清洗管道
处理CSV数据时的黄金组合:
import csv def clean_data(input_file, output_file): with open(input_file, "r", encoding="gbk") as fin, \ open(output_file, "w", newline="", encoding="utf-8") as fout: reader = csv.DictReader(fin) writer = csv.DictWriter(fout, fieldnames=reader.fieldnames) writer.writeheader() for row in reader: # 清洗规则1:去除前后空格 row = {k: v.strip() for k, v in row.items()} # 清洗规则2:空值替换 if not row["手机号"]: continue # 清洗规则3:格式转换 try: row["金额"] = float(row["金额"]) except ValueError: row["金额"] = 0.0 writer.writerow(row) clean_data("原始数据.csv", "清洗后数据.csv")4.3 简易系统监控工具
import psutil import time import smtplib from email.mime.text import MIMEText def system_monitor(interval=60, threshold=90): while True: cpu_percent = psutil.cpu_percent(interval=1) mem_percent = psutil.virtual_memory().percent if cpu_percent > threshold or mem_percent > threshold: alert_msg = f""" 系统警报! CPU使用率: {cpu_percent}% 内存使用率: {mem_percent}% """ send_alert(alert_msg) time.sleep(interval) def send_alert(message): msg = MIMEText(message) msg["Subject"] = "系统监控警报" msg["From"] = "monitor@company.com" msg["To"] = "admin@company.com" with smtplib.SMTP("smtp.company.com") as server: server.send_message(msg) system_monitor() # 启动监控这些案例中我踩过的坑:
- 文件路径处理要用os.path.join(跨平台兼容)
- CSV文件要指定newline=""(防止空行)
- 无限循环要加sleep(避免CPU跑满)
- 资源操作使用with语句(自动关闭)
循环结构看似简单,但真正掌握需要理解几个关键点:条件控制的精确性、边界处理的严谨性、资源管理的可靠性。当你能用循环+函数解决90%的重复工作时,就会明白为什么Python被称为"自动化瑞士军刀"。
编程学习
技术分享
实战经验