How do you use the “def” keyword in Python?

In Python, the def keyword is used to define a function. A function is a reusable block of code that can take parameters and return a value.

Below is an example of defining a function using “def”:

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

# 调用函数
greet("Alice")

Running the above code will produce the following output:

Hello, Alice!

In the example above, the greet function takes a parameter called name and then prints out a greeting within the function body. By calling the greet function and passing in a parameter, we can use this function to greet anyone.

You can also specify multiple parameters within the parentheses after the def statement, separating each parameter with a comma. For example:

def add_numbers(num1, num2):
    return num1 + num2

result = add_numbers(3, 4)
print(result)  # 输出:7

In the example above, the function add_numbers takes two parameters, num1 and num2, and returns their sum. We passed the numbers 3 and 4 to the add_numbers function, assigned the return value to the result variable, and printed the result.

When defining a function using the def keyword, make sure to include any necessary parameters within the parentheses after the function name, and write the function body code within the indented block after the colon.

bannerAds