【发布时间】:2013-04-24 05:28:21
【问题描述】:
我是 Python 新手,无法理解为什么这不起作用。
number_string = input("Enter some numbers: ")
# Create List
number_list = [0]
# Create variable to use as accumulator
total = 0
# Use for loop to take single int from string and put in list
for num in number_string:
number_list.append(num)
# Sum the list
for value in number_list:
total += value
print(total)
基本上,我希望用户输入 123,然后得到 1 和 2 和 3 的总和。
我收到此错误,不知道如何解决。
Traceback (most recent call last):
File "/Users/nathanlakes/Desktop/Q12.py", line 15, in <module>
total += value
TypeError: unsupported operand type(s) for +=: 'int' and 'str'
我只是在我的教科书中找不到这个问题的答案,也不明白为什么我的第二个 for 循环不会迭代列表并将值累积到总计。
【问题讨论】:
标签: python python-3.x