Sum of n numbers in Python using Recursion
In this post, you will learn how to calculate the sum of the first n numbers in Python using recursion. Here's a simple example:
# Function to calculate the sum of first n natural numbers using recursion
def sum_of_n_numbers(n):
if n <= 0:
return 0
else:
return n + sum_of_n_numbers(n - 1)
# Example usage
n = 10
print(f"The sum of the first {n} natural numbers is: {sum_of_n_numbers(n)}")
Output of the above code:
The sum of the first 10 numbers is: 55
Code Explanation:
- The function sum_of_n_numbers takes an integer n as input.
- It uses a base case to check if n is less than or equal to 0, in which case it returns 0.
- Otherwise, it returns n plus the result of calling sum_of_n_numbers with n - 1.
Related Articles
Trigonometric functions Python Numpy
Python convert dataframe to numpy array
Convert binary to decimal in Python
Multiply all elements in list Python
Multiply each element of a list by a number in Python
Python NumPy: Overview and Examples
Convert Python list to numpy array
numpy dot product
Python Pandas Plotting
Pandas string to datetime
Convert Excel to CSV Python Pandas
Python take screenshot of specific window
Read data from excel file using Python Pandas
Quick Introduction to Python Pandas
Python requests GET method
Python Convert XML to CSV
Python iterate list with index
Python add list to list
Python random choice
Python dict inside list
Bouncing ball game code in Python
Remove character from string Python
Python raise keyword