Digit_sum error?


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/0/4?curriculum_id=4f89dab3d788890003000096


I'm receiving an error saying that when it inputs 1000, it gets 12 instead of 1. When i compile this on my computer, i get the correct answer, I'm just wondering why it doesn't work? i've seen other solutions but I'm real confused.


user_input = int(raw_input("enter a number:"))
b = []
c = []
def digit_sum(n):
    total = 0
    q = str(n)
    for char in q:
        b.append(int(char))
    for key in b:
        total += key
        c.append(str(total))
    print int(c[-1])
    
print digit_sum(user_input)


#2

Try to call your function multiple times:

b = []
c = []
def digit_sum(n):
    total = 0
    q = str(n)
    for char in q:
        b.append(int(char))
    for key in b:
        total += key
        c.append(str(total))
    print int(c[-1])

digit_sum(123)
digit_sum(123)

The output is:

6
12

These variables:

b = []
c = []

should be defined inside the function. Now they transfer data between function calls.


#3

dear datasurfer58862:

this is your solution:

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


user_input = int(raw_input("enter a number:"))

#4

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