Python Recursion

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:

Python_Recursion

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

  1. Write a program using the function to find the greatest of three numbers.
  2. Write a python program using the function to convert Celsius to Fahrenheit.
  3. How do you prevent a python print() function to print a new line at the end?
  4. Write a recursive function to calculate the sum of first n natural numbers.
  5. Write a python function to print the first n lines of the following pattern.
***

**       #For n = 3

*
  1. Write a python function that converts inches to cms.
  2. Write a python function to remove a given word from a list and strip it at the same time.
  3. Write a python function to print the multiplication table of a given number.
Was this article helpful?
YesNo

Leave a Comment

Your email address will not be published. Required fields are marked *