【问题标题】:How to write a program in python to get a user input list and sum all the items in it如何在python中编写程序来获取用户输入列表并将其中的所有项目求和
【发布时间】:2017-06-09 09:00:46
【问题描述】:

我是 python 编程的新手,我想知道如何编写一个 python 程序来获取一些用户输入的整数作为列表并将所有项目添加到其中。这是我编写的代码..

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

当我运行这个程序时,它会说,

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'

【问题讨论】:

标签: python add


【解决方案1】:

试试这个修改,输入总是会返回一个字符串,你不能在python中把一个字符串和一个整数相加。

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

另一件事是第一行,你知道列表有多少个值吗?如果是这样,为什么不将您的第一行替换为:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 2021-08-26
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    • 2011-09-05
    相关资源
    最近更新 更多