What is the purpose of the ‘def’ keyword in Python?
In Python, the ‘def’ keyword is used to define functions. By using the ‘def’ keyword, we can create a reusable code block that takes some input (parameters), performs some operations, and returns a result. The purpose of a ‘def’ statement is to define the function’s name, parameters, and body.
Here is an example of how to define a function using “def”:
def add_numbers(a, b):
return a + b
result = add_numbers(2, 3)
print(result) # 输出: 5
In the above example, a function named add_numbers is defined with parameters a and b that returns the sum of the two. By calling add_numbers(2, 3), we pass the arguments 2 and 3 to the function, assign the returned result to the variable “result”, and then print the result of 5.
Therefore, the def keyword allows us to define and call functions in Python.