How to use the def function in Python?

In Python, the keyword “def” is used to define a function.

The syntax for defining a function is as follows:

def 函数名(参数1, 参数2, ...):
    # 函数体(代码块)
    # 可以包含任意数量的语句
    # 可以使用参数进行计算
    # 可以使用 return 语句返回结果

Parameters are optional and can be zero or more in number. The function body is the block of code where the function is executed, and it can contain any number of statements.

Here is a simple example:

def greet(name):
    print("Hello, " + name + "!")

# 调用函数
greet("Alice")

Output:

Hello, Alice!

In the example above, the greet function takes a parameter name and prints the result of “Hello, ” + name + “!”

You can use the return statement in a function body to return a result. Here is an example:

def add(a, b):
    return a + b

# 调用函数
result = add(3, 5)
print(result)

Output:

8

In the example above, the function “add” takes two parameters, a and b, and returns their sum. Calling add(3, 5) will return the result 8, which is then assigned to the variable “result” and printed out.

bannerAds