Digit_Sum (Practice Makes Perfect Lesson)


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw


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


#2

Did you forget to initialize total?


#3

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


#4

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


#5

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