Digit_sum


#1




Traceback (most recent call last):
File "python", line 8, in
File "python", line 5, in digit_sum
TypeError: unsupported operand type(s) for +: 'int' and 'str'


I really don't understand what I did wrong! Can you guys help me?


Replace this line with your code. 
def digit_sum(n):
    total = 0
    n = str(n)
    for i in n:
        total = 0 + i
        print total

print digit_sum(567)


#2

The error problem is that you're trying to add a strings to the integer 0.
There is a really easy fix to this.
You just need to cast i as an int.
Additionally, you're going to have a problem when you say that total is 0 plus int(i), because you're resetting total every time you go through the loop.
I suggest saying total += int(i) OR total = total + int(i), because you want to continually add to it.
Lastly, the lesson is asking you to return total, not print it, so you would return total outside of the for loop, so that it's vertically aligned with for i in n:
I hope this helps, if you have any questions, let me know.


#3

thank you so much! works perfectly now :slight_smile:


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.