循环
一句话解释
循环 是 control 结构 那个 repeats 块 的 code, 要么 fixed 数字 的 次数 (for) or 虽然 条件 是 真 (虽然).
用大白话说
循环 repeats 块的 code. Python 有 two 主要循环类型: for and while.
A for loop iterates over a sequence (list, string, range, etc.): for 项 in 项:. It runs once for each item. The 范围() function is commonly used to loop a specific number of times.
A 虽然 loop repeats as long as a condition is true: 虽然条件:. It is used when you don't know in advance how many iterations are needed. Be careful to ensure the condition eventually becomes false, or the loop runs forever.
break exits a loop immediately. continue skips to the next iteration. else on a loop runs if the loop completes without breaking.
示例
# for loop
for i in range(3):
print(i) # 0, 1, 2
# while loop
count = 0
while count < 3:
print(count)
count += 1
# break and continue
for i in range(5):
if i == 3:
break
if i == 1:
continue
print(i) # 0, 2for 循环 iterate over 序列, 虽然 循环 repeat 直到 条件 是 假, and break/continue control flow.
常见混淆
容易混淆的对象: recursion
关键区别: 循环 repeats code iteratively. Recursion repeats 通过 函数 calling 它自己. 循环 是 通常 更多 efficient in Python; recursion 是 更多 elegant for 树-structured problems 但 risks stack overflow.
相关术语
相关资源
相关课程
- 条件 and 循环
循环 in Python.
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。