Digit Sum - Practice Makes Perfect


I cannot get my code to run! The console no longer has an error message but there is a pop up saying "Oops, try again. Does your digit_sum function take exactly one argument (a positive integer)? Your code threw a "'type' object has no attribute 'getitem'" error. "

My function takes a positive parameter so I don't understand!

def digit_sum(n):
    result = 0
    n = str(n)
    for x in range(len(n)):
        result += str[x]
    return result


Your code is wrong because you haven't defined a list called str, which you are calling in your for loop by using str[x]... You should instead use int(n[x]) That should fix your problem


I was having trouble with this and got it to work with your suggestion above. But I was wondering someone could explain the result = 0 (as in why you need that) and then more importantly what int(n[x]) is actually doing. Also why you need the range function. Thanks!


Hello @jacobson.shellie,

You need that line because in your for loop you are adding up the numbers in the argument passed to the function... So you need to start with a zero and add up the numbers one by one...

You can't add strings to a number, and so what the int() function is doing is that its converting it to a number, and then adds in to result...

Hope this clears out your doubts...