# Python Recursion

## Python Recursion

In this section recursive functions will be discussed. A recursive function is that which calls itself. Recursion can be defined as to define something by itself.

### Python Recursive Function

In Python we can call a function from another function. A function can be called by itself and this type of function will be called recursive function. Consider the following example in which a function is defined that will calculate the factorial of a number entered by the user and the function will be called by itself:

CODE

>>> def factorial(n):

if n==1:

return 1

else:

return(n*factorial(n-1))

>>> x = 5

>>> factorial(x)

OUTPUT

120

Factorial is defined as the product of all numbers or integers from 1 to the number whose factorial is to be calculated. In the above example a function is defined and in the definition of the function a condition is checked that if the number is 1 then return 1 because the factorial of 1 is 1 as 1 * 1 = 1. In the else part again the function is called, this time the value that is passed to the function will be 1 less than the value entered by user.

The function is called by decreasing the number entered by user. The function will be called until the number becomes 1 and the if condition stops the else part to be executed. This is called base condition and if the base condition is not specified then an infinite the recursion will be called an infinite number of times.

Then obtained number will be multiplied by the actual number entered by user and in this way the factorial will be calculated using the recursive function.