Python program that finds the sum of natural numbers up to a given number:

Created with Sketch.

Python program that finds the sum of natural numbers up to a given number:

number = int(input("Enter a number: "))

# Initialize variables
sum = 0

# Check if the number is valid
if number <= 0:
    print("Please enter a positive integer")
else:
    # Find the sum of natural numbers
    for i in range(1, number + 1):
        sum += i
    print("The sum of natural numbers up to", number, "is", sum)

The program prompts the user to enter a number using the input() function, and stores the value in the variable “number”. It then uses an if statement to check if the number is valid, which is a positive integer greater than 0. If the number is not valid, it prints a message saying to enter a positive integer. If the number is valid, it uses a for loop to iterate through the range of natural numbers from 1 to the entered number (inclusive) and for each number, it adds it to the variable “sum”. At the end of the loop, it prints the sum of natural numbers up to the entered number.

Another way to find the sum of natural numbers is by using the mathematical formula for the sum of first n natural numbers which is n(n+1)/2:

number = int(input("Enter a number: "))

if number <= 0:
    print("Please enter a positive integer")
else:
    sum = (number*(number+1))/2
    print("The sum of natural numbers up to", number, "is", sum)

Here, the program takes input from the user and using the mathematical formula it calculates the sum of natural numbers and prints the result.

Both the methods will give you the same output which is the sum of natural numbers up to the entered number. You can use any method that suits your need or preference.

Leave a Reply

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