Confused about Digit_sum


#1




I'm not sure why my code isn't working and reading other answers isn't helping. What is my code doing? Where is my misunderstanding?

When I try "for digit in numberstring" it returns 4 instead of 434. When I try "for digit in range(len(numberstring))" it returns 0 instead of 434.

Thanks.

def digit_sum(n):
    numberstring = str(n)
    result = 0
    for digit in range(len(numberstring)):
        result += int(digit)
        return result


OR


def digit_sum(n):
    numberstring = str(n)
    result = 0
    for digit in numberstring:
        result += int(digit)
        return result


#2

You were so close! All you need to do is change the indentation of your return statement,

so that it is at the same indentation level as your for loop,

def digit_sum2(n):
    numberstring = str(n)
    result = 0
    for digit in numberstring:
        result += int(digit)
    return result

#3

Thanks bandit, you superstar!


#4

You're welcome :slight_smile:


#5

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