Functions in Python
In Python, a function is a reusable block of code that is created to perform a specific task. Functions allow to break code into smaller, more manageable pieces, making it easier to read, understand, and maintain.
Functions in Python typically have the following structure:
def function_name(parameters): # Function body # Code to perform a specific task return result
Here's an explanation of what each part of the above function does:
- def: This keyword is used to define a function in Python.
- function_name: This is the function name.
- parameters: These are optional input values that you can pass to the function. They are enclosed in parentheses and separated by commas.
- Function body: This is where you write the code that defines what the function does. It consists of one or more statements.
- return: This keyword is used to specify the value that the function should return when it is called. Not all functions need to return a value, and in such cases, you can omit the return statement.
Here's an example of a simple Python function that adds two numbers:
def add(x, y): result = x + y return result add_result = add(11, 3) print(add_result)
In this example, add is a function that takes two parameters x and y, adds them together, and returns the result. When we call the function with add(11, 3), it returns 13, which is stored in the variable add_result and printed to the console.
The output of the above code is as follows: