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?
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?
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.
Perhaps this will work:
user_number = input('please enter your number')
sum = 0
for num in user_number:
sum += int(num)
print(sum)
You could convert your input into a list then use list comprehension:
num = input('Enter number: ')
sum([int(i) for i in num])