Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Looping Statements

Find the sum of first n natural numbers - Python Program

Example 1 :

# Sum of first n natural numbers n = int(input("Enter n: ")) total = 0 for i in range(1, n + 1): total += i print(f"Sum of first {n} natural numbers = {total}")

Output

 
OUTPUT  :
Enter n: 10
Sum of first 10 natural numbers = 55
 

Example 2 : Advanced Program

Method 1: Using the Formula

The sum of the first 'n' natural numbers can be calculated directly using the formula: n * (n + 1) / 2. This is the most efficient method as it involves a constant number of operations regardless of the value of 'n'. 

def sum_of_natural_numbers_formula(n): """ Calculates the sum of the first n natural numbers using the mathematical formula. """ if n < 0: return "Input must be a non-negative integer." return n * (n + 1) // 2 # Use // for integer division # Get input from the user try: num = int(input("Enter a positive integer (n): ")) result = sum_of_natural_numbers_formula(num) print(f"The sum of the first {num} natural numbers is: {result}") except ValueError: print("Invalid input. Please enter an integer.")

Output

 
OUTPUT  :
Enter a positive integer (n): 10
The sum of the first 10 natural numbers is: 55
 

Example 3 : Advanced Program

Method 2: Using a Loop

This method involves iterating from 1 to 'n' and accumulating the sum in a variable.

 

def sum_of_natural_numbers_loop(n): """ Calculates the sum of the first n natural numbers using a for loop. """ if n < 0: return "Input must be a non-negative integer." total_sum = 0 for i in range(1, n + 1): total_sum += i return total_sum # Get input from the user try: num = int(input("Enter a positive integer (n): ")) result = sum_of_natural_numbers_loop(num) print(f"The sum of the first {num} natural numbers is: {result}") except ValueError: print("Invalid input. Please enter an integer.")

Output

 
OUTPUT  :
Enter a positive integer (n): 10
The sum of the first 10 natural numbers is: 55