Skip to content

函数

一句话解释

函数 是 reusable 块 的 code 定义 使用 def 那个 takes 输入 (参数) and 返回 输出.

用大白话说

函数是 named, reusable 块的 code. 你定义它 使用 def keyword, give it a name, and specify parameters in parentheses. The body is indented below the definition.

Functions let you avoid repeating code. Instead of writing the same logic multiple times, you write it once in a function and call it wherever needed. Functions also make code easier to test and debug by isolating behavior.

A function can take zero or more parameters, perform operations, and optionally return a value with 返回. If no return statement is executed, the function returns 无.

示例

python
def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

print(greet("Alice"))           # Hello, Alice!
print(greet("Bob", "Hi"))       # Hi, Bob!

函数 是 定义 使用 def, 能 有 默认 参数, and 返回 值 使用 返回.

常见混淆

  • 容易混淆的对象: 方法

    关键区别: 函数 是 standalone. 方法 是 函数 定义 内部 类 and called on 实例 (obj.方法()). 所有 方法 是 函数, 但 不 所有 函数 是 方法.

相关术语

相关资源

相关课程

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表