4. Digit Sum


#1


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

This is the error I get:
Oops, try again. Your function fails on digit_sum(434). It returns None when it should return 11.

I'd be grateful to get an explanation of what I'm doing wrong. Thanks!


def digit_sum(num):
   digits =[]
   num = str(num)
   for dig in num:
       answer = digits.append(int(dig))
       return answer
       print answer


#2

You are overthinking this. Try following this template:

def FUNCTION(PARAMETER):
    VARIABLE = 0
    for INDIVIDUAL_ITEMS in str(PARAMETER):
        VARIABLE += int(INDIVIDUAL_ITEMS)
    return VARIABLE

Make sure you understand how and why this works. If you have any questions on those matters, please, just ask.


#3

a function ends the moment a return keyword is reached, if a return keyword is reached in a loop, the loop will break. So your loop breaks in its first iteration.

when appending to list (unsure why you do this), you don't have to store the result in a variable, append will update the list for you


#4

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