What is Recursion?
Recursion is a function which calls itself.
It is used to directly use a mathematical formula as a function. For example:
factorial(n) = n * factorial(n-1)
This function can be defined as follows:
def factorial(n): if i == 0 or i == 1 : #Base condition which doesn’t call the function any further return i else: return n*factorial(n-1) #Function calling itself
This works as follows:
The programmer needs to be extremely careful while working with recursion to ensure that the function doesn’t infinitely keep calling itself.
Recursion is sometimes the most direct way to code an algorithm.
Exercise on Python Function and Recursion
- Write a program using the function to find the greatest of three numbers.
- Write a python program using the function to convert Celsius to Fahrenheit.
- How do you prevent a python print() function to print a new line at the end?
- Write a recursive function to calculate the sum of first n natural numbers.
- Write a python function to print the first n lines of the following pattern.
*** ** #For n = 3 *
- Write a python function that converts inches to cms.
- Write a python function to remove a given word from a list and strip it at the same time.
- Write a python function to print the multiplication table of a given number.