How to use the “def” statement in Python?

In Python, def is used to define a function. The general form of defining a function is as follows:

def function_name(parameters):
    # 函数体
    # 可执行的代码块
    # 可选的返回语句

In this case, function_name refers to the name of the function, parameters represent the list of parameters for the function, and the function body is the executable code block that can contain any number of statements. Optional return statement is used to specify the return value of the function.

Here is a simple example demonstrating how to define a function and call it.

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

greet("Alice")

The output result is:

Hello, Alice!

In the example above, “greet” is the name of a function and “name” is its parameter. The print statement in the function is used to output a greeting message. By calling greet(“Alice”), we are passing the string “Alice” as a parameter to the greet function and printing out “Hello, Alice!”.

bannerAds