- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to write a recursive function in Python?
A recursive function is a function that calls itself during its execution. This enables the function to repeat itself several times, outputting the result and the end of each iteration. Recursion has something to do with infinity.
Following is an example of recursive function to find the factorial of an integer.
Factorial of a number is the product of all the integers from 1 to that number.
For example, the factorial of 9 (denoted as 9!) is 1*2*3*4*5*6*7*8*9 = 362880.
def factorial(i): if i == 1: return 1 else: return (i * factorial(i-1)) number = 9 print("The factorial of", number, "is", factorial(number))
The factorial of 9 is 362880
In the above program factorial() is a recursive functions as it calls itself. Each function call multiples the number with the factorial of number 1 until the number is equal to one.
For example to place two parallel mirrors facing each other. Any object in between them would be reflected recursively.
def Function(x): if (x < 1): return else: print( x,end = " ") Function(x-1) print(x,end = " ") return x = 5 Function(x)
5 4 3 2 1 1 2 3 4 5
- How to write recursive Python Function to find factorial?
- How to write an empty function in Python?
- How to write a function to get the time spent in each function in Python?
- How to write a python module?
- Recursive function to do substring search in C++
- Recursive function to check if a string is palindrome in C++
- C Program to reverse a given number using Recursive function
- Write a Python program to perform table-wise pipe function in a dataframe
- Write down a python function to convert camel case to snake case?
- How to write an empty function in Java
- How to open a file to write in Python?
- Write a function to delete a Linked List in C++
- How can we create recursive functions in Python?
- Do recursive functions in Python create a new namespace each time the function calls itself?