4 (digit_sum) - I don't understand what I'm doing wrong here


This is my code:

array_of_digits = []

def digit_sum(n):
n = str(n)
for char in n:
x = int(char)
sum_of_digits = sum(array_of_digits)
return sum_of_digits

I keep getting a message that my code is wrong because digit_sum(1000) returns 12 when it should return 1. But when I call digit_sum(1000) and print the result, the console shows an answer of 1. Can anyone help me debug my code?


You are making it too complicated and I can see where it would cause confusion.

Do this

def digit_sum(number):
    list_of_numbers = []
    for digit in str(number):
    return sum(list_of_numbers)

While list comprehension is shorter and cleaner,

def digit_sum(number):
    return sum([int(digit) for digit in str(number)])