Examples
- Hello World Program in Python (How to Print Hello World in Python?)
- Python Program to Add Two Numbers (Sum/Addition Program)
- How to Generate Random Number in Python? (Program)
- Leap Year Program in Python (Check Leap Year or Not in Python)
- Python Program to Check Number is Positive, Negative, or Zero
- Even Odd Program in Python (How to Check Number is Even or Odd?)
- Python Program to Find Largest of 3 Numbers (Greatest of Three Numbers in Python)
- Prime Number Program in Python (Check Prime or Not)
- Python Program to Find Square Root of a Number (Examples)
- Python Factorial Program (How to Find Factorial of a Number in Python?)
- Python Program to Find Prime Numbers in Range
- Python Program to Find Area of Triangle (Different Ways With Examples)
- How to Solve Quadratic Equation in Python? (Program Examples)
- How to Swap Two Numbers in Python? (Program Examples to Swap Variables)
- Python Program to Convert Kilometers to Miles (km to mi) and Vice Versa
- Python Program to Convert Celsius To Fahrenheit (and Fahrenheit to Celsius)
- Program to Check Armstrong Numbers in Python (Code Examples)
- Program for Armstrong Number Between Two Intervals in Python
- Program to Print Multiplication Table in Python (Code Examples)
- Python Program for Fibonacci Series (Print Fibonacci Sequence in Python)
- Program for Sum of n Natural Numbers in Python (Code Examples)
- Program to Print Powers of 2 in Python (Code Examples)
- Python Program to Find Numbers Divisible by Another Number
- Convert Decimal to Binary, Octal and Hexadecimal in Python (Program with Example)
- How to Convert Decimal to Binary in Python? Program with Examples
- How to Convert Decimal to Octal in Python? Program with Examples
- How to Convert Decimal to Hexadecimal in Python? Program and Examples
- How to Convert Binary to Decimal in Python? Program With Examples
- How to Convert Hexadecimal to Octal in Python? Program With Examples
- Program to Find LCM of Two Numbers in Python (Calculate LCM in Python)
- GCD of Two Numbers in Python (Program to Find HCF or GCD)
- GCD of Three Numbers in Python (HCF Program for n Numbers)
- Simple Calculator Program in Python (Basic Calculator Code)
- Find Factors of a Number in Python (Programs and Examples)
- Program to Find Prime Factors of a Number in Python
- How to Find ASCII Value in Python? ASCII Value of Character
Program for Sum of n Natural Numbers in Python (Code Examples)
In programming, efficiency and elegance go hand in hand. When it comes to calculating the sum of n natural numbers in Python, this programming language offers various approaches, each with its own advantages and nuances.
In this post, we will explore different techniques to tackle this simple task. From traditional methods like using loops to more advanced approaches like utilizing mathematical formulas, we leave no stone unturned in our exploration.
Finding the sum of natural numbers in Python is useful whether you are a beginner seeking to grasp the basics or a seasoned programmer searching for new insights.
Through a series of code examples with simple explanations, we will show you how to calculate the sum of n natural numbers using a variety of Python concepts.
Sum of n Numbers in Python Using for loop
Code
# Find sum of n natural numbers in Python with for loop
def calculate_sum(n):
sum = 0
for i in range(1, n + 1):
sum += i
return sum
# Example usage
num = int(input("Enter a number: "))
total_sum = calculate_sum(num)
print(f"The sum of the first {num} natural numbers is: {total_sum}")
Output
Enter a number: 20
The sum of the first 20 natural numbers is: 210
Explanation
-
We define a function calculate_sum that takes a parameter n. We initialize the variable sum to 0, which will store the cumulative sum of the numbers.
-
We use a for loop to iterate from 1 to n (inclusive). In each iteration, we add the current value of i to the sum variable using the += operator.
-
After the loop finishes, we return the final value of sum as the result.
-
In the example, we prompt the user to enter a number using the input function and convert it to an integer using int().
-
We then call the calculate_sum function with the entered number as the argument and store the result in the variable total_sum. Finally, we display the calculated sum to the user.
Sum of n Natural Numbers in Python Using while loop
Code
# Sum of first n natural numbers in Python with while loop
def calculate_sum(n):
sum = 0
i = 1
while i <= n:
sum += i
i += 1
return sum
# Example usage
num = int(input("Enter a number: "))
total_sum = calculate_sum(num)
print(f"The sum of the first {num} natural numbers is: {total_sum}")
Output
Enter a number: 30
The sum of the first 30 natural numbers is: 465
Explanation
-
We define the calculate_sum function that takes a parameter n. We initialize the variable sum to 0, which will store the cumulative sum of the numbers. Additionally, we initialize i to 1, which represents the current number being added to the sum.
-
We use a while loop with the condition i <= n to iterate until the value of i reaches n. Inside the loop, we add the current value of i to the sum variable using the += operator. After that, we increment i by 1 using i += 1.
-
The loop continues until the value of i becomes greater than n. Once the loop finishes, we return the final value of sum as the result.
-
In the example part, we prompt the user to enter a number using the input function and convert it to an integer using int(). We then call the calculate_sum function with the entered number as the argument and store the result in the variable total_sum.
-
Finally, we display the calculated sum to the user.
Sum of n Natural Numbers in Python Using Recursion
Code
# Sum of n natural numbers in Python with recursion
def calculate_sum(n):
if n == 1:
return 1
else:
return n + calculate_sum(n - 1)
# Example usage
num = int(input("Enter a number: "))
total_sum = calculate_sum(num)
print(f"The sum of the first {num} natural numbers is: {total_sum}")
Output
Enter a number: 10
The sum of the first 10 natural numbers is: 55
Explanation
-
We define a recursive function called calculate_sum that takes a parameter n. Inside the function, we have a base case that checks if n is equal to 1. If n is 1, we return 1, as the sum of the first natural number is 1.
-
For any other value of n, we make a recursive call to calculate_sum with n - 1 as the argument and add n to the result of the recursive call. This way, we break down the problem of calculating the sum of n natural numbers in Python into smaller subproblems until we reach the base case.
-
The recursive function keeps calling itself with smaller values of n until it reaches the base case, and then it starts returning the results back up the call stack to calculate the final sum.
-
In the example part, we prompt the user to enter a number using the input function and convert it to an integer using int(). We then call the calculate_sum function with the entered number as the argument and store the result in the variable total_sum.
-
Finally, we print the calculated sum and show it.
Practice More Python Programs:
- Hello World Program in Python
- Python Program to Add Two Numbers
- Generate Random Number in Python
- Leap Year Program in Python
- Even Odd Program in Python
- Python Program to Find Largest of 3 Numbers
- Prime Number Program in Python
- Python Program to Find Square Root of a Number
- Python Factorial Program
- Python Program to Find Area of Triangle
- Solve Quadratic Equation in Python
- Swap Two Numbers in Python
- Python Program to Convert Kilometers to Miles
- Python Program to Convert Celsius To Fahrenheit
- Check Armstrong Numbers in Python
- Print Multiplication Table in Python
- Python Program for Fibonacci Series
- Convert Decimal to Binary, Octal and Hexadecimal in Python
- Find LCM of Two Numbers in Python
- GCD of Two Numbers in Python
- Simple Calculator Program in Python
- Python Matrix Addition Program
- Transpose of Matrix in Python
- Python Matrix Multiplication
- Python Calendar Program