python - python 3 summing numbers from input
问题描述
I'm trying to create a program that takes a number and sums it But for some reason the code wont work
number = input("please enter a four digit number: ")
final = sum(number)
print(final)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
I've attempted to convert it into a integer and string but it keeps saying that each of them is irritable
What am I doing wrong?
解决方案
input
返回一个字符串。因此,您必须先将每个字符转换为整数,然后才能对它们求和
>>> number = '1234'
>>> final = sum(map(int, number))
>>> print(final)
10