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:
- The user is prompted to enter a positive integer using the
input()function, which takes the input as a string and theint()function converts it to an integer. - The variable
sumis initialized to 0. - A
forloop is used to iterate through the numbers from 1 to the input integer, which is done using therange()function. The loop variableitakes on the values from 1 tonum. - The variable
sumis updated in each iteration of the loop by adding the current value ofi. - 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.




