精通Python For循环:语法、示例与进阶模式
Python For循环
通过清晰分步示例,学习在Python中遍历列表、元组、字符串及其他可迭代对象。
视频:Python for循环
什么是Python中的For循环?
for循环遍历 可迭代对象——如列表、元组、字符串——对每个项目执行一次代码块。
For循环语法
for val in sequence:
# 循环体
此处 val 在迭代中捕获 sequence 的每个元素。
循环在最后一个元素后自动终止。正确缩进将循环体与周围代码分开。
For循环流程图

示例:求列表数字之和
# 程序求列表中所有数字之和
# 数字列表
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
# 存储和的变量
sum = 0
# 遍历列表
for val in numbers:
sum = sum + val
print("The sum is", sum)
运行输出:
The sum is 48
range() 函数
range() 生成数字序列。range(10) 产生0到9。
接受可选 start、stop、step 参数:range(start, stop, step)。省略 step 默认为1。
内部 range 是惰性的——按需计算每个数字而非存储所有。这使其对大序列内存高效。
用 list() 物化整个序列:
print(range(10))
print(list(range(10)))
print(list(range(2, 8)))
print(list(range(2, 20, 3)))
输出
range(0, 10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [2, 3, 4, 5, 6, 7] [2, 5, 8, 11, 14, 17]
在for循环中用 range() 常见于数字迭代或需要元素索引时:
# 使用索引遍历列表
genre = ['pop', 'rock', 'jazz']
# 用索引遍历列表
for i in range(len(genre)):
print("I like", genre[i])
输出
I like pop I like rock I like jazz
带 else 的For循环
for 循环可包含可选 else 子句。仅当循环正常完成(未遇 break)时运行 else 块。
示例:
digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")
输出:
0 1 5 No items left.
结合 break 时,else 可指示搜索失败:
# 从记录显示学生成绩
student_name = 'Soyuj'
marks = {'James': 90, 'Jules': 55, 'Arthur': 77}
for student in marks:
if student == student_name:
print(marks[student])
break
else:
print('No entry with that name found.')
输出
No entry with that name found.
Python
- 掌握 C# for 循环:语法、执行流程与实战示例
- 掌握 C++ for 循环:语法、流程图、范围循环与实战模式
- C 语言 for 循环完全指南:语法、机制与实战示例
- 精通Python运算符:全面指南
- 精通Python While循环:语法、示例与最佳实践
- 精通Python循环控制:break 与 continue
- Python 列表操作:创建、访问、修改与进阶技巧
- 精通 Python 字典:创建、操作与进阶技巧
- Python 循环完全指南:for、while、break、continue、enumerate 详解
- 精通 Python range() 函数:从基础到高级用法
- 精通 Python enumerate():为列表、元组、字符串、字典带索引循环
- Java 判断阿姆斯特朗数(自幂数):for 循环与 while 循环实现