【Python入门篇】——Python中循环语句(for循环的基础语法)
warning:
这篇文章距离上次修改已过192天,其中的内容可能已经有所变动。
# Python中for循环的基础语法示例
# 1. 基本用法:遍历一个序列(如列表)
for element in [1, 2, 3, 4, 5]:
print(element)
# 2. 使用range()函数创建数字序列
for i in range(5): # 从0开始到4结束,不包括5
print(i)
# 3. 使用enumerate()获取元素及其索引
for index, value in enumerate(['a', 'b', 'c']):
print(f"Index {index}: {value}")
# 4. 嵌套循环
for i in range(2): # 外循环
for j in range(3): # 内循环
print(f"i={i}, j={j}")
# 5. 使用else语句
for i in range(2):
print(f"This is the {i}th iteration")
else:
print("The for loop completed successfully.")
评论已关闭