In this simple python program, we need to find the sum of natural numbers. It's a number python program.
To understand this example, you should have knowledge of the following Python programming topics:
This python program is to print the sum of n natural numbers. Natural numbers are positive whole numbers like 1, 2, 3 ... some are saying zero is not a natural number, and some argue that zero is also a natural number. So natural numbers can be defined as a set of whole numbers, which are positive, including zero.
In this python program, we need to calculate the sum of N natural numbers in python and print the result. So we have to accept user input and store that in a variable. Then we use an if condition to check the number is greater than zero. if not Break the program. In the
else part, we have to use a while loop in python till the number is greater than zero and add each number to the sum and reduce the number by one to get the next lower number until the number reaches zero. Finally, print the sum after all the iteration of the
while loop is over.
STEP 1: Accept the user's input using input and convert the string to an integer using int() in the python programming language.
STEP 2: Use the
if condition to check the entered number is less than zero and print enter the positive number.
STEP 3: Use the
else condition and initialize a sum variable to zero.
STEP 4: Start a
while loop in python language, where a number greater than zero condition means the loop will continue until the number equal to zero.
STEP 5: Calculate the sum as sum = sum + num and then reduce the num by one.
STEP 6: print the sum variable using the print statement in the python program.
num = int(input("Enter a value of n: ")) if num < 0: print("Enter a positive number") else: sum = 0 while(num > 0): sum += num num -= 1 print("The sum is",sum)
Enter a value of n: 5 The sum of N natural numbers is 15