使用 for 和 range 迭代
遍历数字和序列
使用 for 和 range 迭代 是 CoddyKit 上的免费 Mojo Academy 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Mojo Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Mojo Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Walk Over Items
When you want to visit each value in turn, reach for a for loop. It pulls one item at a time and runs the body for each. 🚶
The for Shape
Write for, a loop variable, the word in, something to walk over, then a colon and an indented block.
for item in things:
print(item)Count with range
To loop a fixed number of times, pair for with range. range(n) yields 0 up to but not including n.
for i in range(3):
print(i)range Stops Before the End
This catches beginners: range(5) gives 0, 1, 2, 3, 4. The end value is excluded, so you get exactly five numbers.
Choose a Start
Give range two values to set a start and end. range(2, 5) walks 2, 3, 4, beginning where you tell it.
for i in range(2, 5):
print(i)Add a Step
A third value sets the step between numbers. range(0, 10, 2) yields the even numbers 0, 2, 4, 6, 8.
for i in range(0, 10, 2):
print(i)Count Downward
A negative step lets range go backward. range(3, 0, -1) produces 3, 2, 1, perfect for a simple countdown.
for i in range(3, 0, -1):
print(i)Loop Over a List
for works on collections too. Iterating a List hands you each element directly, so you rarely need an index.
for name in names:
print(name)Index When You Need It
If you do need positions, loop over range(len(items)) and use the index to reach into the collection.
for i in range(len(items)):
print(items[i])Accumulate Across a for
Just like while, a for loop can build a total. Initialize before the loop, then add inside the body each pass.
var total = 0
for i in range(1, 5):
total += iPrefer for for Known Counts
Use for with range when the number of passes is known up front. It is clearer and harder to break than a manual while.
Quick Check
You write for i in range(5). Which exact sequence of numbers does i take across the loop?
Recap
A for loop visits each item, and range generates numbers with start, end, and step. Remember the end value is excluded. 🎯
常见问题解答
「使用 for 和 range 迭代」课时是免费的吗?
是的 — 「使用 for 和 range 迭代」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Mojo Academy 课程的其余内容,请升级到 CoddyKit PRO。 Mojo Academy 课程共包含 4 节课。
「使用 for 和 range 迭代」这节课中我会学到什么?
遍历数字和序列 你通过在浏览器中直接运行的动手代码来练习 Mojo Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Mojo Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Mojo Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「使用 for 和 range 迭代」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Mojo Academy 课中编写并运行代码吗?
能。每节 Mojo Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 使用 if/else 做选择
- 使用 while 循环
- 使用 for 和 range 迭代
- break、continue 与提前退出