使用for循环在列表中添加值

Aar*_*ron 3 python python-3.x

我是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)
Run Code Online (Sandbox Code Playgroud)

基本上,我希望用户输入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'
Run Code Online (Sandbox Code Playgroud)

我只是在我的教科书中找不到答案,并且不明白为什么我的第二个for循环不会迭代列表并将值累加到total.

Gar*_*ber 10

您需要先将字符串转换为整数,然后才能添加它们.

尝试更改此行:

number_list.append(num)
Run Code Online (Sandbox Code Playgroud)

对此:

number_list.append(int(num))
Run Code Online (Sandbox Code Playgroud)

或者,更多Pythonic的方法是使用该sum()函数,并将map()初始列表中的每个字符串转换为整数:

number_string = input("Enter some numbers: ")

print(sum(map(int, number_string)))
Run Code Online (Sandbox Code Playgroud)

但请注意,如果您输入类似"123abc"的内容,您的程序将崩溃.如果您有兴趣,请查看处理异常,特别是a ValueError.

  • 我同意这是一个有效的解决方案,但基于命名,将其添加到名为"number_list"的列表时将其转换为整数更有意义.否则他每次使用数字时都需要施放. (2认同)