Python初学者必问:循环结构使用示例
在Python编程中,循环结构是常用的一种控制流程工具。以下是几种常见的循环结构及其使用示例:
for
循环:- 遍历序列(列表、元组)或其他可迭代对象。
# 遍历一个列表
numbers = [1, 2, 3]
for num in numbers:
print(num)
- 遍历序列(列表、元组)或其他可迭代对象。
while
循环:- 当条件满足时,执行循环内的代码。
count = 0
while count < 5:
print("This is loop number", count + 1)
count += 1
- 当条件满足时,执行循环内的代码。
break
语句:- 当满足特定条件(如退出循环)时,执行该语句。
for num in range(10):
if num == 5:
break # 退出循环
print(num)
- 当满足特定条件(如退出循环)时,执行该语句。
以上示例展示了Python中常见的循环结构使用方法。
还没有评论,来说两句吧...