I’m trying to make my first Python calculator which can add given values given by user. The problem is that sometimes we may have several values to add i.e. a + b is not only the addition we have a + b + d + g + h + ... so I have defined a range up to n where n is the user input.
Now the problem is that if the user gives a value of 5 in the range, then how to map the each and every value in that range to enter the values to add?
The code:
def main():
print("how many no.s are we dealing with?");
n=int(input(""));
for i in range(n):
print("addition:");
Cutting things short, I just want a user to first type how many values would be adding and then the user has to type all those values to be typed for the calculator to add them.
It’s like if the user has a range of 3 numbers [a + b + c] then the user would type 3 in the first prompt then he would type a, b, c values in each prompt to give out the total.
Notice the lack of
;How this works is that the result is initialized to 0. Then every time the loop iterates the user is asked for a number. That number is then added to the result.
There is, however, an easier way:
How this works is:
in line 1: you ask the user to enter a string and store it
in line 2: you do a whole lot… I’ll examine it piece by piece:
sum_string.split('+')takes the string inputted by the user and turns it into a list. for example:1+2+ 45'.split('+') => ['1','2',' 45'][float(i) for i in ['1','2',' 45']] => [1,2,45]this is called list comprehension. It is awesome and totally worth looking up
sum([1,2,45]) => 48`in line 3: we print out the result. I’m not really sure what you want to do with it
Note: this will not work with negative numbers as it stands but can be adapted to do so…