Let's learn a Python program in this article. Let's learn a Python program that finds the sum of all the numbers upto a given number using recursion. recursion is a technique where a function calls itself directly or indirectly is known as recursion.
Limitation of this program
====================================
Please note that your laptop/ personal computer might limit only 999 recursive function calls for a given Python program. so if you provide a number that is more than 999 so this well through a recursion error saying limit exceeded as shown in the last output.
Use Recursion to Print The Sum of All Numbers Up to a Given Input
Let's define a function named as find_sum() and pass the given input value to it as n. now using the if statement check if an equals to 0 or 1 return the value of n. using the else part return n plus the recursive function find_sum() with reduced value of n by 1.
def find_sum(n):
if n == 0 or n == 1:
return n
return n + find_sum(n - 1)
In the main program take a variable name as number and using the input function call ask a user to enter the number then convert the number to an integer using the type conversion. Once the user inputs the number, call the recursive function find_sum() providing an input value number as an input argument.
Store the return value of the recursive function into a variable named as result. Using the print function, call print the sum of all the numbers and display the result.
number = int(input("Enter a Number : "))
result = find_sum(number)
print(f"Sum of All Numbers Upto {number} : {result}")
Code
==============
def find_sum(n):
if n == 0 or n == 1:
return n
return n + find_sum(n - 1)
number = int(input("Enter a Number : "))
result = find_sum(number)
print(f"Sum of All Numbers Upto {number} : {result}")
Output
=============
Enter a Number : 5
Sum of All Numbers Upto 5 : 15
Output
=============
Enter a Number : 54
Sum of All Numbers Upto 54 : 1485
Output
==============
Enter a Number : 800
Sum of All Numbers Upto 800 : 320400
Output : Recursion Limit Exceeds
========================================
Enter a Number : 999
Traceback (most recent call last):
File "C:/Users/Public/Projects/vlogs/main.py", line 12, in <module>
result = find_sum(number)
[Previous line repeated 995 more times]
File "C:/Users/Public/Projects/vlogs/main.py", line 6, in find_sum
if n == 0 or n == 1:
RecursionError: maximum recursion depth exceeded in comparison
Conclusion
=====================
Execute the above program by providing random integer value as an input to the Python program note down the results.
Comment it down below if you have any suggestions to improve the Python program
0 Comments