跳到主要内容

Python中如何定义一个函数?

参考答案:

在Python中,你可以使用def关键字来定义一个函数。函数的基本结构如下:

def function_name(parameters):
    """This is a docstring. It briefly describes what the function does."""
    # This is the body of the function.
    # You can put your code here.
    return result  # Return a result, if needed.

这里是一个具体的例子,定义了一个函数add_numbers,这个函数接受两个参数并返回它们的和:

def add_numbers(a, b):
    """This function adds two numbers and returns the result."""
    result = a + b
    return result

你可以通过以下方式调用这个函数:

sum = add_numbers(5, 3)
print(sum)  # 输出: 8

在这个例子中,add_numbers是函数名,ab是参数,函数体中的result = a + b是执行的操作,return result是返回的结果。当你调用add_numbers(5, 3)时,函数会执行a + b的操作并返回结果8。