Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Line by line input sum

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading