Python Program to Find the Sum of Natural Numbers

Here’s an example Python code to find the sum of natural numbers:

# Get input from user for the last number
n = int(input("Enter a positive integer: "))

# Compute the sum of natural numbers using a loop
sum = 0
for i in range(1, n+1):
    sum += i

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

In this code, we first prompt the user to enter a positive integer using the input() function and convert it to an integer using the int() function. We then use a for loop to iterate over the range of natural numbers from 1 to the last number entered by the user. Within the loop, we add each natural number to a variable called sum. Finally, we use the print() function to display the result to the user using f-strings to format the output.

When you run this code, it should prompt you to enter a positive integer. After you enter a number, it should compute the sum of the natural numbers from 1 to the entered number and display the result, similar to the following:

Enter a positive integer: 10
The sum of first 10 natural numbers is 55

Note that you can modify the messages or the formatting of the output as needed.

Related Examples

1. Python Program to Print Hello world!

2. Calculate the multiplication and sum of two numbers

3. Python Program to Find the Square Root

4. Python Program to Calculate the Area of a Triangle

5. Python Program to Solve Quadratic Equation

6. Python Program to Swap Two Variables

7. Python Program to Generate a Random Number

8. Return the count of a given substring from a string

9. Print the following pattern

10. Python Program to check if the given number is a palindrome number

11. Python Program to print multiplication table form 1 to 10

12. Print downward Half-Pyramid Pattern with Star (asterisk)

13. Python Program to Convert Kilometers to Miles

14. Python Program to Check if a Number is Positive, Negative or 0

15. Print the sum of the current number and the previous number in Python

Leave a Reply

Your email address will not be published. Required fields are marked *

Wordpress Social Share Plugin powered by Ultimatelysocial
Wordpress Social Share Plugin powered by Ultimatelysocial