Stuck on Practice makes Perfect 4. Digit sum


#1



I'm trying to run a loop to turn the characters of the number into a list of string characters, and then turn those characters into integers and sum them. But I'm getting an error message that "digit_sum(434) returns 1302 instead of 11"
My code is obviously wrong, but I don't see where. Can someone point me in the right direction? Thanks!

n = int(input("type in your number:"))
def digit_sum(n):
    string = str(n)
    list = []
    for char in string:
        list.append(n)
    d = 0
    for a in list:
        number = int(a)
        d = d + number  
    return d
    print d


#2

here:

list.append(n)

you append n (which is the whole number) to list, shouldn't this be something else?


#3

hi @hwh13, i feel like you do not need your first line of code. The way I did it was by using an if/while/else statement that looks like this:

if n >= 0:
        sum = 0

try adding the while (hint: use a %)and the else. Hope this helps!


#4

yes, that was it; thanks! I'd been stuck for days on that one.


#5

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