Files
marqdo/doc/tutorial/08-循环.md
cflmyandCursor 34915e3b16 docs: align remaining tutorial chapters with markup v0.3
Teach bold-as-code, italic-as-return, link-index, and bracket-marked calls across chapters 1–8/10–14 and Skill reference so teaching matches the runtime.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 13:18:28 +08:00

180 lines
2.1 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 第 8 章:循环
## 8.1 遍历循环:`- [项](集合)`
Marqdo 用 `-`(无序列表)表达循环。遍历列表用 `- [项](集合)`:
```markdown
# main
`篮子` =
| 果 |
|----|
| 苹果 |
| 梨 |
| 桃 |
- [果](篮子)
> print text=今天吃`果`
```
输出:
```text
今天吃苹果
今天吃梨
今天吃桃
```
- `[果](篮子)` —— 遍历 `篮子` 列表,每个元素绑定到 `果`
- 循环体内用 `` `果` `` 引用元素(独立 `>` 调用中变量要反引号)
反引号形式等价(可混用):
```markdown
- [`果`](`篮子`)
> print text=`果`
```
## 8.2 遍历字典:遍历键
`Map`(字典)用 `- [键](映射)` 遍历**键**:
```markdown
# main
`分类` =
| 苹果 | 黄瓜 |
|------|------|
| 水果 | 蔬菜 |
- [键](分类)
> print text=`键`
```
输出:
```text
苹果
黄瓜
```
> 遍历字典遍历的是键;要取值,用链接取元 `[键](集合)`(见[第 9 章](./09-集合.md))。
## 8.3 while 循环:`- 条件`
`-` 后直接写条件就是 while 循环:
```markdown
# main
**n = 3**
- `n` > 0
> print text=`n`
**n = n - 1**
```
输出:
```text
3
2
1
```
> 循环体内用 `**…**` 语句更新变量。
## 8.4 嵌套循环
循环可以嵌套:
```markdown
# main
`外层` =
| 项 |
|----|
| A |
| B |
`内层` =
| 项 |
|----|
| 1 |
| 2 |
- [o](外层)
- [i](内层)
> print text=`o``i`
```
输出:
```text
A1
A2
B1
B2
```
## 8.5 循环 + 分支组合
```markdown
# main
`数字` =
| 值 |
|----|
| 1 |
| 2 |
| 3 |
| 4 |
- [n](数字)
1. `n` >= 3
> print text=`n` 是大数
2. *
> print text=`n` 是小数
```
> 循环体里的 `1.` / `2.` 是分支语句(见[第 7 章](./07-条件分支.md)),与 `-` 循环嵌套使用。
## 8.6 完整示例:累计求和
```markdown
# main
`数字` =
| 值 |
|----|
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
**sum = 0**
- [n](数字)
**sum = sum + n**
> print text=总和:`sum`
```
输出:
```text
总和:15
```
## 8.7 下一步
你已经掌握循环了。接下来学习[第 9 章:集合(表格)](./09-集合.md),深入理解列表、字典与记录。