循环语句基础
Python 中的循环语句主要包括for循环和while循环,用于重复执行代码块。循环的声明和使用可以通过以下方式实现:
# for 循环遍历序列foriinrange(5):print(i)# while 循环基于条件count=0whilecount<5:print(count)count+=1循环输入与输出
使用内置函数可以方便地进行循环中的输入和输出操作:
defmain():# 循环读取用户输入直到输入 quitwhileTrue:name=input("Enter your name (or 'quit' to exit): ")ifname.lower()=='quit':breakprint(f"Hello,{name}!")if__name__=="__main__":main()常用循环控制语句
Python 提供了丰富的循环控制关键字:
defmain():numbers=[1,2,3,4,5,6,7,8,9,10]# 遍历列表fornuminnumbers:# 跳过偶数ifnum%2==0:continueprint(f"Odd number:{num}")# 找到第一个大于 5 的奇数后退出ifnum>5:break# 循环正常结束时执行 elseforiinrange(3):print(f"Iteration{i}")else:print("Loop completed normally")if__name__=="__main__":main()循环与迭代器
循环与迭代器密切相关,Python 的for循环本质上是对迭代器的遍历:
defmain():text="Iterator"# 字符串本身就是可迭代对象forcharintext:print(char,end=' ')print()# 使用 iter() 显式创建迭代器iterator=iter(text)whileTrue:try:char=next(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(f"Flattened:{flat}")if__name__=="__main__":main()循环操作示例
字符串遍历和分割是常见操作,可以使用循环配合内置方法实现:
defmain():text="apple,orange,banana"# 使用 for 循环手动分割字符串current=""forcharintext:ifchar==',':print(current)current=""else:current+=charprint(current)# 输出最后一个部分# 更简洁的方式:使用 split()print("--- Using split() ---")forfruitintext.split(','):print(fruit)if__name__=="__main__":main()安全循环处理
为防止无限循环和资源耗尽,推荐使用安全的循环写法:
defmain():# 设置最大迭代次数防止无限循环max_attempts=10attempts=0whileattempts<max_attempts:user_input=input("Enter a number: ")ifuser_input.isdigit():print(f"You entered:{int(user_input)}")breakattempts+=1print(f"Invalid input.{max_attempts-attempts}attempts remaining.")else:# 循环正常结束(未触发 break)print("Maximum attempts reached.")# 使用 enumerate 获取索引和值,避免手动维护计数器items=["apple","banana","cherry"]forindex,iteminenumerate(items):print(f"{index}:{item}")if__name__=="__main__":main()自定义循环工具
实现自定义的循环辅助函数可以加深对迭代的理解:
defmy_enumerate(iterable,start=0):"""自定义枚举函数"""index=startforiteminiterable:yieldindex,item index+=1defmy_range(start,stop=None,step=1):"""自定义范围生成器"""ifstopisNone:stop=start start=0current=startwhile(step>0andcurrent<stop)or(step<0andcurrent>stop):yieldcurrent current+=stepdefmain():# 测试自定义 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 循环语句的主要概念和操作,从基础用法到高级技巧,为开发者提供了全面的参考。