by BehindJava

# Write a program to Find the Sum of Natural Numbers

Home » python » Write a program to Find the Sum of Natural Numbers

In this tutorial we are going to Find the Sum of Natural Numbers

# Python Program to Find the Sum of Natural Numbers

``````number = int(input("Please Enter any Number: "))
total = 0
for value in range(1, number + 1):
total = total + value
print("The Sum of Natural Numbers from 1 to {0} =  {1}".format(number, total))
#using while loop:
num = int(input("Enter a number: "))

if num < 0:
print("Enter a positive number")
else:
sum = 0
# use while loop to iterate until zero
while(num > 0):
sum += num
num -= 1
print("The sum is",sum)  ``````

# Python program to find the sum of natural numbers using recursive function

``````def recur_sum(n):
if n &lt;= 1:
return n
else:
return n + recur_sum(n-1)

num=int(input(“enter the no of terms”))
if num &lt; 0:
print(&quot;Enter a positive number&quot;)
else:
print(&quot;The sum is&quot;,recur_sum(num))``````

Explanation:

• Firstly, create a function called recur_sum and we pass a parameter ‘n’ if it is less than or equal to 1 it returns n else it returns n and adds n-1 term with it. Example: Assign 5 as n,then it goes to else statement returns 5 and recursion takes place then it takes n as 4 gets into else statement and again recursion takes place and assigns n as 3 and gets into else statement and this process process continues till n is equal to 1
• Take user input
• if it is less than 0 it asks to enter positive number else it prints the result.