WSQ07 – sum of numbers

the program has to sum all the integers in range between two numbers given by the user. at first I did it with the range function but the teacher asked for a loop to make the operation so I did it like this.

ask for two integers, one low and one high but if the user enters the a lower number in the high number place the program wont work properly so I added a condition to correct the numbers:

x = low

y = high

if x > y:

    x,y = y,x

that will exchange the values between the x and y and so continue the program correctly. now to do the sum i added a variable with a value of 0 and used a while loop:

z = 0

while x != y:

   z = z+x

   x += 1

that will add x to z and rise x one number to keep the loop until x=y but will stop before the last number, if x=1 and y=5 then the operation would be 1+2+3+4 excluding the high number, to fix this I added a last operation at the end to print the sum the resulting z with the high number y:

print (z+y)

and it’s done.

question – how do I tell the program to ask again for an integer if the user enters a string?

my code in github:

https://github.com/nazare52/progra/blob/master/wsq07.py

 

CC BY 4.0 WSQ07 – sum of numbers by sergio is licensed under a Creative Commons Attribution 4.0 International License.

Comments are closed.