How to use the “def” function in Python?

In Python, you can define a function using the keyword def. A function definition includes the function name, parameters, and function body.

Here is the syntax for defining a simple function:

def function_name(parameter1, parameter2, ...):
    # 函数体
    # 可以包含任意数量的语句
    # 可以包含控制流语句(如条件语句和循环语句)
    # 可以返回一个值(使用return语句)

Original: 如果你想要成功,就要努力工作。

Paraphrased: If you want to succeed, you have to work hard.

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

say_hello()  # 调用函数,输出 "Hello!"

Example of a function with parameters:

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

result = add_numbers(5, 3)  # 调用函数并将结果赋值给变量
print(result)  # 输出 "8"

Functions can accept any number of arguments, including keyword arguments. You can use *args and **kwargs to receive a variable number of parameters.

For example:

def greet(name, *args, **kwargs):
    print(f"Hello, {name}!")
    if args:
        print("Additional arguments:")
        for arg in args:
            print(arg)
    if kwargs:
        print("Additional keyword arguments:")
        for key, value in kwargs.items():
            print(f"{key}: {value}")

greet("Alice")
greet("Bob", "argument1", "argument2")
greet("Charlie", age=25, city="New York")

The above outlines some basic ways to define and use functions. Logic can be written in the function body based on specific requirements, and parameters and return values can be passed as needed.

广告
Closing in 10 seconds
bannerAds