On this blog I’ll develop a code that asks the user a range of numbers and the program will return the sum of all numbers of that range.
To get started, we need to ask the user for the range of numbers with an input:
After that, is necessary to convert the inputs to integer numbers so our program can run without problems. Every number in python needs to have a type of number, it depends of what you need to do. For this program, I’ll use integers because this program does not need something more elaborated.
We also need a mathematical counter, I’ll explain later why. For now, we’ll give it the value of zero.
Then, a loop is needed to do the whole mathematical process, because the program will sum each number of the range consecutively.
While programming the loop, you need to be careful so you don’t code things unnecesarily. (Like I did) All the comments are the lines that wasn’t needed but I wrote at first, until the teacher helped me out to optimize the code.
The logic of the program is simple, the “cont” variable will sum the numbers of the range and the line #10 is the one that will increment the value of each number of the serie as it advances.
Finally, we just print the result with the syntax that we already know.
That’s it! We’re done with it!.
As always, I uploaded my code so you can check it.
Sum of numbers (WSQ07) by paogarcia2401 is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.