- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Environmental Science
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- articles and Answers
- Effective Resume Writing
- HR Interview articles
- Computer Glossary
- Who is Who
How can we create recursive functions in Python?
Recursion is a programming method, in which a function calls itself one or more times in its body. Usually, it is returning the return value of this function call. If a function definition follows recursion, we call this function a recursive function.
Also Read : How to get a list of parameter names inside Python function?A recursive function has to terminate to be used in a program. It terminates, if with every recursive call the solution of the problem is becomes smaller and moves towards a base case, where the problem can be solved without further recursion. A recursion can lead to an infinite loop, if the base case is not met in the calls.
Example
The following code returns the sum of first n natural numbers using a recursive python function.
def sum_n(n):
if n== 0:
return 0
else:
return n + sum_n(n-1)
This prints the sum of first 100 natural numbers and first 500 natural numbers
print(sum_n(100))
print(sum_n(500))
Output
C:/Users/codegyan/~.py
5050
125250
Advertisements
ads