How to use the ‘def’ function in Python?
In Python, the “def” keyword is used to define a function. The general syntax for function definition is as follows:
def function_name(parameters):
# 函数体
# 可以包含多条语句
# 可以有返回值
In which, function_name is the name of the function, parameters are the parameters of the function (optional), and the function body is the specific implementation of the function.
The following is a simple example that demonstrates how to define a function and then call it:
def greet(name):
print("Hello, " + name + "!")
greet("Alice") # 输出 Hello, Alice!
In the given example, a function named greet is defined with a parameter named name. The function’s implementation prints a greeting. We then call the greet function, passing in the parameter “Alice”, which outputs Hello, Alice!
In addition to the print function mentioned above, the function body can also include any other statements. Functions can have return values, which are specified by using the return statement. For example:
def add(a, b):
return a + b
result = add(3, 4)
print(result) # 输出 7
In the example above, a function named add is defined with two parameters, a and b. The function adds these two parameters together and returns the result. Then, we call the add function, passing in the arguments 3 and 4, assign the return value to the variable result, and print the result 7.
It is important to note that after defining a function, it must be called using the function name followed by parentheses. Parameters can be passed as needed, or not at all.