Practice makes perfect 4/15


#1

https://www.codecademy.com/en/courses/learn-python/lessons/practice-makes-perfect/exercises/digitsum?action=lesson_resume&link_content_target=interstitial_lesson

Write a function called digit_sum that takes a positive integer n as input and returns the sum of all that number’s digits. For example: digit_sum(1234) should return 10 which is 1 + 2 + 3 + 4.

Wondering why my code below isn’t working. Please help. (local variable ‘sum’ referenced before assignment on line 5)

sum = 0
def digit_sum(n):
    number = str(n)
    for digit in number:
        sum = sum + int(digit)
    return sum

print(digit_sum(1234))

#2

sum isn’t defined inside the function, so that will cause problem in the behavior of your program