Write a Python Program to Find the Sum of Natural Numbers

In Python, it’s very simple to find the sum of natural numbers using a loop.

The program will ask the user for a positive integer and then use a for loop to iterate through the numbers from 1 to the input integer and add them together.

Here’s the Python program to find the sum of natural numbers:

num = int(input("Enter a positive integer: "))
sum = 0

for i in range(1, num + 1):
    sum += i

print("The sum of natural numbers from 1 to", num, "is", sum)

Explanation of the code:

  1. The user is prompted to enter a positive integer using the input() function, which takes the input as a string and the int() function converts it to an integer.
  2. The variable sum is initialized to 0.
  3. A for loop is used to iterate through the numbers from 1 to the input integer, which is done using the range() function. The loop variable i takes on the values from 1 to num.
  4. The variable sum is updated in each iteration of the loop by adding the current value of i.
  5. Finally, the sum is printed out along with a message to indicate what the sum represents.

In summary, this program is a simple and effective way to find the sum of natural numbers in Python.