What is the usage of “def” in Python?

In Python, the keyword “def” is used to define functions. By using the “def” keyword, a function can be created in the program.

The general syntax for function definitions is as follows:

def 函数名(参数列表):
    函数体

The function name is a custom name for the function, the parameter list is the parameters that the function will receive, and the function body is the specific execution logic of the function.

Here is a simple example:

def say_hello():
    print("Hello, world!")
    
say_hello()

The above code defines a function named say_hello, which takes no parameters and prints “Hello, world!” in the function body. By calling the say_hello() function, you can output “Hello, world!” in the program.

In addition, the function can also accept parameters and return a value. For example:

def add_numbers(a, b):
    return a + b
    
result = add_numbers(2, 3)
print(result)

The code above defines a function called add_numbers that takes two parameters, a and b, and returns the sum of a and b in the function body. By calling the add_numbers(2, 3) function, the result can be assigned to result and the value of result is then output as 5.

To sum it up, the usage of the “def” keyword is to define a function by specifying its name, parameter list, and body to describe its behavior, thus achieving code encapsulation and reusability.

bannerAds