- 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
- 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.
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
- Related Questions & Answers
- Recursive program to linearly search an element in a given array using C
- What are Python function attributes?
- Write C program to find Exponent Power Series
- How To Reduce the Array to 0 by decreasing elements by 1 or replacing at most K elements by 0
- How can we create recursive functions in Python?
- How to calculate gross salary of a person using C Program
- How to make a chain of function decorators in Python?
- How to Implement Stack Operations Using Array using C
- See (stage) your website before switching your DNS
- How to convert temperature from degree centigrade to Fahrenheit using C
- What is SQL ?
- How to redirect HTTP to HTTPS Using htaccess
- How to Calculate Area of Rectangle using C Program
- How to reads customer number and power consumed and prints amount to be paid using C
- How to Calculate Area of Right angle Triangle using C Language
- How to calculate sum of 5 subjects and find percentage Using C Program
ads