
循环语句基础Python 中的循环语句主要包括for循环和while循环用于重复执行代码块。循环的声明和使用可以通过以下方式实现# for 循环遍历序列foriinrange(5):print(i)# while 循环基于条件count0whilecount5:print(count)count1循环输入与输出使用内置函数可以方便地进行循环中的输入和输出操作defmain():# 循环读取用户输入直到输入 quitwhileTrue:nameinput(Enter your name (or quit to exit): )ifname.lower()quit:breakprint(fHello,{name}!)if__name____main__:main()常用循环控制语句Python 提供了丰富的循环控制关键字defmain():numbers[1,2,3,4,5,6,7,8,9,10]# 遍历列表fornuminnumbers:# 跳过偶数ifnum%20:continueprint(fOdd number:{num})# 找到第一个大于 5 的奇数后退出ifnum5:break# 循环正常结束时执行 elseforiinrange(3):print(fIteration{i})else:print(Loop completed normally)if__name____main__:main()循环与迭代器循环与迭代器密切相关Python 的for循环本质上是对迭代器的遍历defmain():textIterator# 字符串本身就是可迭代对象forcharintext:print(char,end )print()# 使用 iter() 显式创建迭代器iteratoriter(text)whileTrue:try:charnext(iterator)print(char,end )exceptStopIteration:breakprint()if__name____main__:main()嵌套循环处理多维数据时可以使用嵌套循环defmain():# 二维列表matrix[[1,2,3],[4,5,6],[7,8,9]]# 嵌套 for 循环遍历二维列表forrowinmatrix:forelementinrow:print(element,end\t)print()# 使用列表推导式更 Pythonic 的方式flat[elementforrowinmatrixforelementinrow]print(fFlattened:{flat})if__name____main__:main()循环操作示例字符串遍历和分割是常见操作可以使用循环配合内置方法实现defmain():textapple,orange,banana# 使用 for 循环手动分割字符串currentforcharintext:ifchar,:print(current)currentelse:currentcharprint(current)# 输出最后一个部分# 更简洁的方式使用 split()print(--- Using split() ---)forfruitintext.split(,):print(fruit)if__name____main__:main()安全循环处理为防止无限循环和资源耗尽推荐使用安全的循环写法defmain():# 设置最大迭代次数防止无限循环max_attempts10attempts0whileattemptsmax_attempts:user_inputinput(Enter a number: )ifuser_input.isdigit():print(fYou entered:{int(user_input)})breakattempts1print(fInvalid input.{max_attempts-attempts}attempts remaining.)else:# 循环正常结束未触发 breakprint(Maximum attempts reached.)# 使用 enumerate 获取索引和值避免手动维护计数器items[apple,banana,cherry]forindex,iteminenumerate(items):print(f{index}:{item})if__name____main__:main()自定义循环工具实现自定义的循环辅助函数可以加深对迭代的理解defmy_enumerate(iterable,start0):自定义枚举函数indexstartforiteminiterable:yieldindex,item index1defmy_range(start,stopNone,step1):自定义范围生成器ifstopisNone:stopstart start0currentstartwhile(step0andcurrentstop)or(step0andcurrentstop):yieldcurrent currentstepdefmain():# 测试自定义 enumeratecolors[red,green,blue]foridx,colorinmy_enumerate(colors,1):print(f{idx}.{color})# 测试自定义 rangeprint(Custom range:,list(my_range(1,10,2)))if__name____main__:main()性能注意事项循环操作在 Python 中需要特别注意性能和效率问题避免在循环中进行重复计算将不变量提取到循环外优先使用内置函数和生成器表达式处理大数据集考虑使用map()、filter()或列表推导式替代简单循环对于数值计算考虑使用 NumPy 等库进行向量化操作以上代码示例涵盖了 Python3 循环语句的主要概念和操作从基础用法到高级技巧为开发者提供了全面的参考。