In Python, a function is a block of code that performs a specific task. Here are the basic ingredients of a function:
Function name: The name of the function is used to call it and should be descriptive of the task it performs.
Parameters: These are the input values that the function receives. They are optional and can be used to customize the function's behavior.
Function body: This is the block of code that is executed when the function is called. It should contain the logic of the function.
Return value: The return statement is used to send a value back to the caller. It is optional and can be used to send back the result of the function's computation.
Here's an example of a simple function that takes two numbers and returns their sum:
def add_numbers(x, y): """ Adds two numbers together and returns the sum. """ result = x + y return result |
In this example, the function name is add_numbers, and it takes two parameters x and y. The function body contains a single line that adds x and y together and stores the result in a variable called result. Finally, the return statement is used to send the value of result back to the caller.
To call this function, you would simply pass two arguments to it, like this:
sum = add_numbers(3, 4)print(sum) # Output: 7 |
In this example, the function is called with the arguments 3 and 4, which are passed to the x and y parameters of the function. The resulting sum of 7 is returned and assigned to the variable sum.