0

So I am trying to get a user's input and add it's numbers together.

input('Enter number: ')

And then say the user entered 458 then I wanted to add all it's digits up? I have tried using + but it doesn't work. Any solutions?

3 Answers3

3

The problem you probably came across is that you have a string.

>>> answer = input('Enter number: ')
Enter number: 458
>>> print(type(answer))
<class 'str'>

But if you want to add each of the digits up, you'll need to convert each digit to an int. Thankfully, because we have a string here, we can actually iterate through each character in the string (try not to read it as "each digit in the number", because we have a string '458' here with characters '4', '5', '8'.)

>>> total = 0
>>> for character in answer:
...     total = total + int(character)
... 
>>> print(total)
17

Notice how I convert each character in the string to an integer, then add it to a total integer.

TerryA
  • 58,805
  • 11
  • 114
  • 143
0

Perhaps this will work:

user_number = input('please enter your number')


sum = 0
for num in user_number:
    sum += int(num)

print(sum)
SatoriBlue
  • 93
  • 4
0

You could convert your input into a list then use list comprehension:

num = input('Enter number: ')
sum([int(i) for i in num])
dkhara
  • 695
  • 5
  • 18