# 4. digit_sum

#1

Hey! Can you tell me what could be wrong here? Thanks!

``````def digit_sum(a):
result = 0
for i in str(a):
result=result+int(i)
return result
digit_sum(456)``````

#2

Your return statement is at the wrong indent level. Your for loop currently execute once. Why? Well, in the first run of your for loop, it will encounter the return statement, which means the function (including the loop inside the function) ends. The return should be at the same indent level as you for loop so it can loop over all values

#3

Ok, thanks a lot for your help, It worked

#4

Writing just this (same as above):

``````def digit_sum(n):
result = 0
for i in str(n):
result = result + int(i)
return result``````

gives you the go ahead but when you introduce something like:

``````digit_sum(34567)
digit_sum(-4567)``````

What I mean is:

``````def digit_sum(n):
result = 0
for i in str(n):
result = result + int(i)
return result

digit_sum(34567)``````

no problem but:

``````def digit_sum(n):
result = 0
for i in str(n):
result = result + int(i)
return result

digit_sum(34567)
digit_sum(-4567)``````

big problem - you have this error on the console:

``````Traceback (most recent call last):
File "python", line 8, in <module>
File "python", line 4, in digit_sum
ValueError: invalid literal for int() with base 10: '-'``````

and this, on the pop-up box;

``Oops, try again. Your code looks a bit off--it threw a "invalid literal for int() with base 10: '-'" error. Check the Hint if you need help!``

I just don't want to pass through this lesson, I'm interested in knowing what's going on because I'm confused.

#5

You can't call `int(i)` on a non-integer. `-` is a not a integer, if you want to do this, you will have to build in a check if `i` is a integer, if it is, add it to result, otherwise to do nothing

#6

Thanks @stetim94 for the exposition