Sum of Numbers (‘for’ loops)

The next program ask the user for two numbers, the first is the lower limit of a range of numbers, and the second is the maximum. The program then takes all the numbers in the given range and makes the sum of all the numbers in the given interval, including the limits.

The source code is the given:

of Numbers

 

n1=int(input(“Enter the lower limit of the range “))

n2=int(input(“Enter the higher limit of the range “))

 

if(n2<n1):

    print(“The lower limit must be a lower number than the second”)

sumnum=0

 

for num in range(n1,n2+1):

    sumnum=sumnum+num

 

print(“The sum is “,sumnum)

The first thing the program does is validate that the user don’t crash the program, it simply applies a conditional that tells the user that the inputs are incorrect, thus the program wont do nothing.

In the program we can see a for loop. The for loop is used when we know how many times we are going to be in a loop, or when we need a given variable that will be incremented in every run that we make of the loop. This is used very often to navigate inside arrays and other arranges. 

The for loop in Python is used in conjuction with the range command, wich gives us an array of integers when we type the lower and the upper limit; but beware, the upper limit is not inclusive, thus you must use a +1.

Then the program uses this loop and navigates the array adding to the accumulative of the two numbers before the next number in the array, thus making the sum of all the numbers in the array. 

At the end the program prints the accumulative sum of all the integers in the array. 

This is for my of my

CC BY 4.0 Sum of Numbers (‘for’ loops) by Nuel is licensed under a Creative Commons Attribution 4.0 International License.

Comments are closed.