How to define a function in Python?

In Python, you can define functions using the keyword def. The basic syntax for defining a function is as follows:

def 函数名(参数1, 参数2, ...):
    函数体

In this context, the function name is an identifier used to call the function; parameters are values passed to the function when called; the function body is a series of code blocks that perform specific tasks.

Here is a simple example, defining a function for addition:

def sum(a, b):
    result = a + b
    return result

In the example above, the function is named sum and it takes two parameters, a and b, it then adds them together and returns the result.

After defining a function, you can call the function by using its name and passing the appropriate parameters, as shown below:

result = sum(2, 3)
print(result)  # 输出 5

In the code above, the sum(2, 3) calls the sum function and passes the arguments 2 and 3. After the function is executed, it returns the result 5, which is then assigned to the result variable, and the result is printed using the print function.

bannerAds