- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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.
Example 1
def factorial(i): if i == 1: return 1 else: return (i * factorial(i-1)) number = 9 print("The factorial of", number, "is", factorial(number))
Output
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.
Example 2
def Function(x): if (x < 1): return else: print( x,end = " ") Function(x-1) print(x,end = " ") return x = 5 Function(x)
Output
5 4 3 2 1 1 2 3 4 5
- Related Articles
- How to write recursive Python Function to find factorial?
- How to create a simple Recursive Function in Golang?
- How to write an empty function in Python?
- How to write a function to get the time spent in each function in Python?
- Haskell Program to create a simple recursive function
- Recursive function to do substring search in C++
- Recursive function to check if a string is palindrome in C++
- Function to copy string (Iterative and Recursive)
- Golang program to implement recursive anonymous function
- Do recursive functions in Python create a new namespace each time the function calls itself?
- C Program to reverse a given number using Recursive function
- Using a recursive function to capitalize each word in an array in JavaScript
- How can we create recursive functions in Python?
- Write a Python program to perform table-wise pipe function in a dataframe
- How to define a function in Python?
