Need Help Dealing with inputs

Question:

Begginer Question, So i have this problem where i receive a lot of inputs in different lines like:

Inputs:
1
2
0
2
1

And i want to sum them or store them in any kind of list to Sum them latter, how can i do this?

I mean, i could store a variable for each one of them like:

a1 = int(input())
a2 = int(input())
ax = int(input())
....
and then 
result = a1+a2+ax...
print(result)

but that’s not pratical. Someone can explain me on how to store and sum them in a list?

i think that i could do something like this too

    x = int(input())
and use
    x += x    
Asked By: Murilo MSA

||

Answers:

Just use python lists:

inputlist = []

for i in range(5):
    inputlist.append(int(input))

result = sum(inputlist)

Note, I just put a 5 there to ask for 5 values. Ask however many inputs you want.

Answered By: Otto Hanski

you could use a while loop, or a for loop for it. If you are provided the number of inputs in advance in a variable x, you can start with a for loop.

x = int(input("Number of Inputs> "))  # If you know the certain number of inputs
                                      # that you are going to take, you can directly replace them here.
answer = 0

for i in range(x):
    answer += int(input())

print("Answer is", answer)

If you do not know the amount of inputs in advance, you can implement a while loop that will take input until a non-integer input is given.

answer = 0
while True:
    x = input()
    try:
        x = int(x)  # Tries to convert the input to int
    except ValueError:  # If an error occurs, ie, the input is not an integer.
        break   # Breaks the loop and prints the answer
    
    # If all goes fine
    answer += x

print("Answer is", answer)

And obviously, we also have a classic alternate to all this, which is to use python list, these can store numbers and we can process them later when printing the answer. Although, I would have to say if the number of input is large, then the most efficient manner is to use either of the above solution due to their memory footprint.

x = int(input("Number of Inputs> "))  # If you know the certain number of inputs
                                      # that you are going to take, you can directly replace them here.
inputs = []

for i in range(x):
    inputs.append(int(input()))

print("Answer is", sum(inputs))
Answered By: xcodz-dot

I’m also a beginner, but here’s a solution I came up with:

new_list = []

for entry in range(10):
    new_list.append(int(input()))

print(sum(new_list))
Answered By: andrew
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.