This task was about making a programm that asks the user for two integers. The user will read that the first number she/he types will be the begining of a serie of numbers and the second will be the end of the serie. Then the program will take all the numbers inclued in that serie, and add them all, so it will be an inclusive sum of numbers.

The task is meant for us to learn to use loops, and i selected to use the For Loop. This is so far one of the hardest parts of programing i’ve learned and according to what i´ve read is one of the most powerful.

A for loop consts of various parts, i understand it like this:

for (variable we´ll use for repeating the process) in (under what conditions it will repeat):

what to do once we’re inside the loop

The code i wrote is:

print(“Hey! This programm will ask you for two integers, the beginning”)            
print(“and the end of a serie of numbers”)
print(“So the program will display the addition of all the nubers”)
print(“within the range of the ones you provide us”)
print()
x = int(input(‘Please type the first number of your serie: ‘))                  
print()
y = int(input(‘Please type the second number of the serie: ‘))                  
c = 0
print()
for i in range(x, (y+1)):                                                       
    c = c + i

print(‘The sum of ‘,x, ‘ to ‘, y, ‘ (inclusive) is: ‘, c)

I was thinking of ther solutions but once i figured how to do it with for, i realize it only takes me two lines.

So, the explaining of my code is that first i asked the numbers to the user. Then i had to set the first number that i had to add, i choose 0 because it wont affect my operation. Then wrote the for loop. I started with ‘for’ and the i followed with the variable that will repeat the process of the loop, i selected the letter ‘i’. Then i type ‘in range (x,(y+1))’ which means that the loop must repeat in the range of the numbers the user gave me. If you are wondering why i set ‘y+1’ thats because the function range is composed to start where it is told (or zero if it doesn´t say where to start) and to end where it is told minus one. So to fix this i simple add it one.

The the body of the loop is that c = c+i. Lets remember that C starts being zero, so the first will be ‘0 + i’ where ‘i’ will start being the first number the user gave me. So after that the loop will start all over again, now ‘i’ will be ‘i+1’ because of the body and ‘c’ again will be the previous c we saved on memory plus the actual value of i. This will be performed until ‘i’ reaches the second value the user gave us. Then the sum of all number, inclusive, will be done and ready to be printed.

CC BY 4.0 Sum of numbers by fersabal is licensed under a Creative Commons Attribution 4.0 International License.