Please help: 4. digit_sum


#1



Hi, can someone tell me what is wrong here? It seems that the code works correctly and performs the condition, but for some reason it does not pass the check. Who has any ideas? Thanks a lot.


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


Oops, try again. Your function fails on digit_sum(434). It returns 12 when it should return 11.


count = 0
numbers = []

def digit_sum(n):
    if n >= 0:
        n = str(n)
        for i in range(len(n)):
            numbers.insert(i, int(n[i]))
            count = sum(numbers)
        return count
        
    else:
        print "You entered an invalid value!"
    
print digit_sum(12345)
print digit_sum(12345)


#2
count = 0
numbers = []

The first variable needs no initital value. To ensure that each run of the function starts with a fresh slate, the list should be defined in that scope.

def digit_sum(n):
    numbers = []

#3

Thank you very much, this was realy helpful! Now everything works fine! :slight_smile:


#4

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