观察TypeError:不确定如何修复此错误

时间:2017-12-03 23:20:09

标签: python

我的要求是在用户输入的整数中添加数字。首先将整数转换为String,然后将字符串转换为list。将字符串转换为列表后,我将迭代列表中的每个元素并执行求和以显示最终结果。

我在互联网上看过一些使用' map'和'总和'命令获得最终结果。我想使用列表来迭代元素。 有人可以帮我找出程序中的错误吗?

number=int(input("Enter the number:"))  
total=0  
mystr=str(number)  
mylist=list(mystr)  
print mylist  
for element in mylist:  
    total=total+element  
print total  

我正在观察下面提到的错误,

RESTART: C:\SKANAKAV\at&t\Python\Aricent_Python\python_scripts\Find the Sum of Digits in a Number\test_map.py 
Enter the number:234
['2', '3', '4']

Traceback (most recent call last):
  File "C:\SKANAKAV\at&t\Python\Aricent_Python\python_scripts\Find the Sum of Digits in a Number\test_map.py", line 16, in <module>
    total=total+element
TypeError: unsupported operand type(s) for +: 'int' and 'str'

2 个答案:

答案 0 :(得分:0)

使用total = total + int(element)

答案 1 :(得分:0)

当您遍历列表时,元素仍然是字符串。 那是什么引发了错误。您需要在添加之前转换为整数。

此外,您的输入以字符串形式出现,但随后将其转换为整数,然后立即将其转换回字符串。只需跳过这些转换。

此代码将执行您想要的操作:

number=input("Enter the number:")
mylist=list(number)
total=0
print(mylist)
for element in mylist:
    total += int(element)
print(total)
相关问题