Python 循环结构实战:从基础语法到自动化脚本

Python 循环结构实战:从基础语法到自动化脚本
1. Python循环结构基础while与for的实战入门第一次接触Python循环时我被那个自动打印100份报表的脚本震惊了——原来3行代码就能完成我整天的工作。循环结构就像编程世界的复制粘贴神器但比CtrlC/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_onlyTrue): 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第{attempt1}次尝试失败{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, encodingutf-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, encodinggbk) as fin, \ open(output_file, w, newline, encodingutf-8) as fout: reader csv.DictReader(fin) writer csv.DictWriter(fout, fieldnamesreader.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(interval60, threshold90): while True: cpu_percent psutil.cpu_percent(interval1) 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] monitorcompany.com msg[To] admincompany.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被称为自动化瑞士军刀。