编写 def 函数
Python 风格,动态且宽容
编写 def 函数 是 CoddyKit 上的免费 Mojo Academy 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Mojo Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Mojo Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Functions Bundle Logic
A function packages a piece of work under a name so you can run it whenever you like, instead of repeating code. 🧩
Meet the def Keyword
The def keyword defines a function the Python way: relaxed about types and easy to write while you explore an idea.
def greet():
print("Hello from Mojo")Calling Your Function
Defining a function does not run it. You call it by writing its name followed by parentheses, and the body executes.
greet()Passing in Arguments
Put parameters in the parentheses to feed data in. Here name becomes a value you can use inside the body.
def greet(name):
print("Hi", name)Types Are Optional in def
In a def you may skip type annotations entirely. Mojo lets the value flow dynamically, just like Python does.
def double(x):
return x * 2Returning a Value
The return keyword hands a result back to whoever called the function, ending the function right there.
def add(a, b):
return a + bArguments Are Mutable Copies
Inside a def, arguments act like local copies you can reassign freely without touching the caller value.
def bump(x):
x = x + 1
return xdef Feels Like Python
If you know Python, def is instantly familiar: same syntax, same forgiving feel, now running on Mojo.
Great for Quick Experiments
Because it asks for so little, def shines when prototyping or scripting, where speed of writing matters most.
Indentation Defines the Body
Everything indented under the def line is the function body. Mojo, like Python, uses indentation to group code.
def info():
print("line one")
print("line two")Docstrings Document Intent
A string on the first body line is a docstring: a short note describing what the function does for future readers.
def area(r):
"Return circle area."
return 3.14 * r * rQuick Check
Think about how def handles type annotations.
Recap
You met def: the Python-style function in Mojo. Types are optional, arguments are mutable copies, and it is perfect for quick, forgiving code. 🎯
常见问题解答
「编写 def 函数」课时是免费的吗?
是的 — 「编写 def 函数」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Mojo Academy 课程的其余内容,请升级到 CoddyKit PRO。 Mojo Academy 课程共包含 4 节课。
「编写 def 函数」这节课中我会学到什么?
Python 风格,动态且宽容 你通过在浏览器中直接运行的动手代码来练习 Mojo Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Mojo Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Mojo Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「编写 def 函数」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Mojo Academy 课中编写并运行代码吗?
能。每节 Mojo Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 编写 def 函数
- 编写 fn 函数
- 何时选择哪一种
- 返回类型与 None