Line by line input sum

Question:

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?

Asked By: Murilo MSA

||

Answers:

Just as previous post suggested, here to summarize it – it’s easy to break down line by line if you know the mechanic.

When you read input numbers, they are separated by space, and they’re strings. So you have to do split() then convert to integer by using map.

Notes – Credit to @Mechanic. Labor is mine ... 😉

a1 = sum(map(int, input().split()))    # enter input sep. by space, so it need to split first and convert from string to int
a2 = sum(......)                       # sum(generator expression here...)
a3 = sum(.......) 

# Or you just want to save the list of numbers first:
a1 = list(map(int, input().split()))      # save all numbers into a list

# then do the sum() later - if you need to
a1_total = sum(a1) 
Answered By: Daniel Hao

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.

Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.