Beginner question
I have an input like this:
5 8 9 2 1 # = 25
1 2 0 1 9 # = 13
5 7 9 10 2 # = 33
That is separated per lines and between values/individual inputs we have an space.
I need to write code that stores the sum of these values line by line and store them into a variable, like a1 = the sum of input line 1, a2 = the sum of input line 2.
a1 will be 25, a2 will be 13, and a3 will b 33.
Which function i use to write this the way that I want?
Extra question: How to store them individually in a list or a variable? Like, a1 = the inputs in the line1, a2 = inputs in the line2, without adding them, I can only do this with lists?
>Solution :
You can do this:
def main():
a = input()
l = list()
total = 0
while a != 'e':
for token in a.split():
try:
total += int(token)
except ValueError:
return -1
l.append(total)
total = 0
a = input()
print(l)
return 0
if __name__ == "__main__":
main()
… type ‘e’ as input to quit.
If you enter a non-numeric character (like a letter) the function automatically quits and the program ends.