Digit_Sum (Practice Makes Perfect Lesson)



Oops, try again. Did you create a function called digit_sum? Your code threw a "local variable 'total' referenced before assignment" error.

def digit_sum(n):
    x = str(n)
    for char in x:
        total = total + int(char)
    return total


Did you forget to initialize total?


Could you help explain that, please?

Also, I tried this with total and it worked. Don't know what was the error in my earlier code still. Here I have used total again.

def digit_sum(n):
x = str(n)
result = list(map(int, x))
total = sum(result)
return total


Refresh the page and see if it still runs. Did you initialize total?


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