-4

I'm new to python programming and I want to know how to write a python program to get a some user input integers as a list and add all the items in it.This is the code I've written..

A=list(input("Enter the values of the list "))  
total=0  
for a in A:    
    total=total+a  
print(total)  

When I run this program it says,

Traceback (most recent call last):
  File "C:/Users/Jayaweera/Desktop/Python programming/51E5-sum all the items in a list.py", line 4, in <module>
    total=total+a
TypeError: unsupported operand type(s) for +: 'int' and 'str'
12

1 Answer 1

0

Try this modification, input will always return a string and you can't sum a string with an integer in python.

A=list(input("Enter the values of the list "))  
total=0  
for a in A:    
    total=total+int(a)  
print(total) 

Another thing is that first line, do you know how many values the list will have? If so why won't replace your first line with:

A = list()
totalElementsOfList = 100 # assuming it is for example 100 elements
for iteration in range(100):
    A.append(input("Value #" + str(iteration) + " :"))

for element in A:
    total += int(element)

print(total)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.