Python Program to calculate the sum of first N natural numbers

Write a Python program to find the sum of the first n natural numbers, where n is provided by the user. Natural numbers are positive integers starting from 1.

Input-Output Examples

plaintext
Example 1:
Input: Enter a number: 10
Output: The sum of the first 10 natural numbers is: 55
Example 2:
Input: Enter a number: 5
Output: The sum of the first 5 natural numbers is: 15

Algorithm to calculate the sum of first N natural numbers

  1. Start
  2. Take input: Prompt the user to enter a number n.
  3. Initialize a variable to store the sum: Set the sum to 0.
  4. Use a loop to add numbers from 1 to **n**:
    • Iterate through the numbers from 1 to n.
    • Add each number to the sum.
  5. Display the result: Print the sum of the natural numbers.
  6. End

Python Program to calculate the sum of first N natural numbers

python
# Python program to find the sum of natural numbers

# Take input from the user
n = int(input("Enter a number: "))

# Initialize sum variable to 0
sum_of_numbers = 0

# Calculate the sum of natural numbers from 1 to n
for i in range(1, n + 1):
    sum_of_numbers += i  # Add each number to the sum

# Display the result
print(f"The sum of the first {n} natural numbers is: {sum_of_numbers}")

Code Explanation

  1. Taking input from the user:
    The program uses the input() function to take a number n from the user. The input is converted to an integer using int().
  2. Initializing the sum variable:
    The program initializes a variable sum_of_numbers to 0, which will store the sum of the natural numbers.
  3. Using a loop to calculate the sum:
    A for loop is used to iterate through the numbers from 1 to n. During each iteration, the current number is added to sum_of_numbers. For example, if n = 5, the loop computes 1 + 2 + 3 + 4 + 5 = 15.
  4. Displaying the output:
    The print() function is used to display the sum of the natural numbers using an f-string to format the output neatly.

Python

8511

692

Related Articles