To understand this example, you should have the knowledge of following Python programming topics:
In the program below, we've used an if else statement in combination with a while loop to calculate the sum of natural numbers upto num.
# Python program to find the sum of natural numbers up to n where n is provided by user # change this value for a different result num = 16 # uncomment to take input from the user #num = int(input("Enter a number: ")) if num < 0: print("Enter a positive number") else: sum = 0 # use while loop to iterate un till zero while(num > 0): sum += num num -= 1 print("The sum is",sum)
The sum is 136
Note: To test the program, change the value of num.
Here, we store the number in num and display the sum of natural numbers up to that number. We use
while loop to iterate until the number becomes zero.
We could have solved the above problem without using any loops using a formula directly.
Your turn: Modify the above program to find the sum of natural numbers using the formula below.
For example, if n = 16, the sum would be (16*17)/2 = 136.