

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 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.
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/TutorialsPoint1/~.py 5050 125250
- Related Questions & Answers
- What are MySQL stored functions and how can we create them?
- How we can store Python functions in a Sqlite table?
- How can we combine functions in MySQL?
- How we can create singleton class in Python?
- Do recursive functions in Python create a new namespace each time the function calls itself?
- How can we create MySQL views?
- How can we calculate the Date in MySQL using functions?
- How can we distinguish between MySQL IFNULL() and NULLIF() functions?
- Auxiliary Space with Recursive Functions in C Program?
- How can we create multicolumn UNIQUE indexes?
- How we can create a dictionary from a given tuple in Python?
- How can we create a custom exception in Java?
- How can we create a login form in Java?
- Can we create nested TitiledBorder in Java?
- How can we stuff a string with another one using MySQL functions?