A function allows you to define a reusable block of code that can be executed many times within your program.
Functions allow you to create more modular and [DRY](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself) solutions to complex problems.
While Python already provides many built-in functions such as `print()` and `len()`, you can also define your own functions to use within your projects.
Functions are blocks of code that can be reused simply by calling the function. This enables simple, elegant code reuse without explicitly re-writing sections of code. This makes code more readable, easily debugged, and error-proof.
A function always returns a value,The `return` keyword is used by the function to return a value, if you don't want to return any value, the default value `None` will be returned.
- Python interprets the function block only when the function is called and not when the function is defined. So even if the function definition block contains some sort of error, the python interpreter will only reveal this when the function is called.
Using functions in our programs can help to explicitly handle the execution of specific type of algorithms.
One useful method is recursion. Recursion may not only save time but can explictly handle the code and execute the given task.
```python
def factorial(n):
if n==0:
return 1
else:
return n*factorial(n-1)
```
In this example we are computing factorial of a given number without using any loops. Whenever we use recursion we must define a base case. The remaining cases can recursively call the `factorial` function with a number as the argument without the need for loop statements to perform the itertion.
**Walkthrough**
We need to find the factorial of 5 (`5!`)
1. First we call `factorial(5)`
2.`n` is not equal to `0` so the flow jumps to the else statement
3. In the else statment, we return the product of `n` and the `factorial` function with `n-1` as an argument.
4. This continues until `n` is equal to `0`, our base case, where we return `1`.
5. The final return value will be the product of all values between `1` and `5` (e.g. `1 * 2 * 3 * 4 * 5`) or `120`.