Python 基础知识:for 与 while 的行为差异
作者:野牛程序员:2025-12-21 12:17:13python阅读 2059
Python 基础知识:for 与 while 的行为差异
# /*
# Python 基础知识:for 与 while 的行为差异
# --------------------------------------------------------
# 功能:
# 1) 展示 for 与 while 的核心区别
# 2) 说明适用场景与循环控制方式的不同
# 3) 通过示例直观比较两者的执行流程
# */
print("示例一:固定次数循环的对比")
print("使用 for:")
for n in range(5):
print("for 输出:", n)
print("使用 while:")
i = 0
while i < 5:
print("while 输出:", i)
i += 1
print("-" * 40)
print("示例二:遍历列表的差异")
data = [10, 20, 30]
print("使用 for:")
for v in data:
print("for 取到元素:", v)
print("使用 while:")
idx = 0
while idx < len(data):
print("while 取到元素:", data[idx])
idx += 1
print("-" * 40)
print("示例三:无法确定循环次数时的差异")
print("使用 while:")
x = 1
while x < 50:
print("值:", x)
x = x * 2 + 1
print("-" * 40)
print("示例四:for 搭配 iterable,while 搭配条件表达式")
text = "ABC"
print("for 遍历字符串:")
for ch in text:
print("字符:", ch)
print("while 模拟遍历字符串:")
t = 0
while t < len(text):
print("字符:", text[t])
t += 1
# /*
# 输出示例(简化版):
# 示例一(固定次数):
# for 输出: 0
# ...
# while 输出: 0
# ...
# ----------------------------------------
# 示例二(遍历列表):
# for 取到元素: 10,20,30
# while 取到元素: 10,20,30
# ----------------------------------------
# 示例三(次数未知):
# 值: 1
# 值: 3
# 值: 7
# 值: 15
# 值: 31
# ----------------------------------------
# 示例四(for 遍历 iterable):
# 字符: A
# 字符: B
# 字符: C
#
# 要点总结:
# 1) for 依赖“可迭代对象”,负责逐个取出元素;
# 2) while 依赖“条件表达式”,条件满足时持续执行;
# 3) for 适合固定次数或明确的序列遍历;
# 4) while 适合循环次数无法提前确定的情况;
# 5) for 的索引管理自动处理;while 需要手动维护计数器;
# 6) for 结构更简洁;while 更灵活,但必须小心避免死循环。
# */野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

