Python, known for its simplicity and readability, provides a powerful platform for various numerical computations. In this tutorial, we’ll explore how to write a Python program to find the sum of natural numbers using a `for`

loop.

Understanding this fundamental concept not only strengthens your grasp of Python but also lays the groundwork for more complex algorithms. Let’s dive into the details and learn how to harness the versatility of Python to efficiently calculate the sum of natural numbers.

**Code for Finding the Sum of Natural Numbers in Python:**

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# Python program to find the sum of natural numbers up to n where n is provided by user #to take input from the user num = int(input("Enter a number: ")) if num < 0: print("Enter a positive number") else: sum = 0 # use while loop to iterate un till zero while(num > 0): sum += num num -= 1 print("The sum is",sum) |

This is a Python program that calculates the sum of natural numbers up to a user-specified number ‘n’.

The program starts by taking input from the user in the form of a string and then casting it to an integer using the int() function.

It then checks if the number entered by the user is less than zero, and if it is, it prints “Enter a positive number” and the program exits. If the number is greater than or equal to zero, it proceeds to the next block of code.

The program declares a variable ‘sum’ and initializes it to zero. Then, it uses a while loop to iterate through the natural numbers up to ‘n’ (inclusive). The while loop continues to execute as long as the value of ‘num’ is greater than zero.

In each iteration of the while loop, the program adds the value of ‘num’ to the ‘sum’ variable and then decrements the value of ‘num’ by 1.

After the while loop completes execution, the program prints the final value of the ‘sum’ variable, which is the sum of the natural numbers up to ‘n’.

Overall, this program takes input from the user, checks if it is a positive number, and then uses a while loop to iterate through the natural numbers up to the user-specified number and calculate the sum of those numbers.