* recursion

i believe that once we know function we should introduce a little bit of recursion techniques which nothing but an advancement of function.

* fixed formatting, grammar, removed unnecessary words/sentences
This commit is contained in:
Himanshu Bag
2018-11-05 23:30:28 +05:30
committed by Paul Gamble
parent f4ff1d961d
commit d7bb602130

View File

@ -126,6 +126,32 @@ result = s(1, 2)
print(x) # error - x is not defined
print(double(4)) # prints 8
```
- 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 interpretar will point that out only when the function is called.
- 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 interpretar will point that out only when the function is called.
### Recursion
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`.
### More Information:
- <a href='https://docs.python.org/3/tutorial/controlflow.html#defining-functions' target='_blank' rel='nofollow'>Python 3 Docs: Defining Functions</a>