Back to tree

⚙️ 函数:打包好的榨汁机⚙️ Function: A Packed-Up Juicer

上一片,小电脑学会了转圈干活。小卖部又开了果汁台:每杯都要洗、切、榨、倒。同样四步,写了一遍又一遍。这一片,把它们打包成一台机器。 Last leaf, the little computer learned to run laps. Now the snack stand adds a juice bar: wash, cut, squeeze, pour — for every cup. The same four steps, written again and again. This leaf packs them into one machine.

第 1 步:一台榨汁机Step 1: One juicer

同样的四步,能只写一次吗?Can the same four steps be written just once?

榨汁机:水果进,果汁出
能!函数就是打包好的一段步骤。像榨汁机:水果进,果汁出。里面怎么洗、怎么切,不用再操心。给它起个名字,比如 榨汁()。喊一声名字就开工,这叫“调用”。 Yes! A function is a packed-up set of steps. Like a juicer: fruit in, juice out. How it washes and cuts is no longer your worry. Give it a name, like juice(). Say the name and it starts — that is a “call”.

每次的水果不一样,机器怎么知道?Different fruit each time — how does the machine know?

第 2 步:参数进,返回值出Step 2: Parameter in, return value out

翻倍机:参数 4 进,返回值 8 出
靠参数!参数是你递进去的东西。返回值是机器交回来的结果。图里这台会翻倍:放进 4,交回 8。放进 5,就交回 10。同一台机器,参数一换,结果就变。 Parameters! A parameter is what you hand in. The return value is what the machine hands back. This one doubles: put in 4, get back 8. Put in 5, get back 10. Same machine — change the parameter, change the result.

打包好的机器,还能搬去哪儿用?Where else can a packed machine go?

第 3 步:写一次,到处用Step 3: Write once, use everywhere

一张配方卡:店里、家里、学校都能用
哪儿都能用!店里、家里、学校,用的是同一张配方。要改配方,只改一处,处处跟着变。程序员天天用函数:print 打印,max 找最大。大程序,就是很多小函数拼起来的。 Anywhere! Shop, home, school — all share one recipe card. Change the recipe once, and every copy follows. Coders use functions all day: print shows text, max finds the biggest. Big programs are many small functions snapped together.

🎮 你来开机器(30 秒)🎮 Your turn: run the machine (30 seconds)

道理讲完了。先选水果、拨杯数,调用几次榨汁机。再接 4 关:猜猜机器交回什么。Theory done. First pick a fruit and the cups, and call the juicer a few times; then take 4 rounds: guess what the machine hands back.

一句话记住它:函数 = 打包好、有名字的一段步骤;参数递进去,返回值交回来,写一次到处用。 Remember it in one line: a function = a named, packed-up set of steps; parameters go in, a return value comes out — write once, use everywhere.
喊名字就开工:调用 榨汁()Say its name to start it: call juice() 参数进,返回值出:翻倍(4) → 8Parameter in, return value out: double(4) → 8 写一次到处用:改一处,处处跟着变Write once, use everywhere: fix once, fixed everywhere
内容参考 OpenStax 等公开教材,多来源核对 · AI 生成、人工审核 · 发现错误欢迎指正,帮这片叶子长得更好。 Based on OpenStax and other open textbooks, cross-checked across sources · AI-generated, human-reviewed · Spotted a mistake? Tell us — help this leaf grow.