Introduction
The sum of natural numbers is a basic mathematical operation. Natural numbers are positive integers starting from 1. This tutorial will guide you through creating a Python program that calculates the sum of all natural numbers up to a specified number.
Problem Statement
Create a Python program that:
- Takes a positive integer as input.
- Calculates the sum of all natural numbers from 1 to the specified number.
- Displays the sum.
Example:
- Input:
n = 10 - Output:
The sum of natural numbers up to 10 is 55
Solution Steps
- Take Input from the User: Use the
input()function to get a positive integer from the user. - Convert Input to an Integer: Convert the input string to an integer using
int(). - Calculate the Sum: Use a loop or a formula to calculate the sum of natural numbers up to the specified number.
- Display the Result: Use the
print()function to display the sum.
Python Program
# Python Program to Find the Sum of Natural Numbers
# Author: https://www.rameshfadatare.com/
# Step 1: Take input from the user
n = int(input("Enter a positive integer: "))
# Step 2: Calculate the sum using the formula
# Sum of first n natural numbers = n * (n + 1) / 2
if n > 0:
sum_natural = n * (n + 1) // 2 # Use // for integer division
# Step 3: Display the result
print(f"The sum of natural numbers up to {n} is {sum_natural}")
else:
print("Please enter a positive integer.")
Explanation
Step 1: Take Input from the User
- The
input()function prompts the user to enter a positive integer. The input is converted to an integer usingint().
Step 2: Calculate the Sum
- The sum of the first
nnatural numbers can be calculated using the formula:
This formula is efficient and avoids the need for a loop.
Step 3: Display the Result
- The
print()function is used to display the sum of natural numbers up ton. If the user enters a non-positive integer, the program will prompt the user to enter a positive integer.
Output Example
Example:
Enter a positive integer: 10
The sum of natural numbers up to 10 is 55
Example:
Enter a positive integer: 5
The sum of natural numbers up to 5 is 15
Example (Invalid Input):
Enter a positive integer: -3
Please enter a positive integer.
Conclusion
This Python program demonstrates how to calculate the sum of natural numbers up to a specified number using a mathematical formula. It is a simple yet powerful example for beginners to understand basic arithmetic operations and user input handling in Python.