Digit_sum


#1

Hi all,

I have this odd occurrence with my code. The code below fails and returns the error message "Oops, try again. Your function fails on digit_sum(434). It returns 4 when it should return 11."


def digit_sum(n):
    string = str(n)
    total = 0
    
    for x in string:
        total += int(x)
        return total

yet, if I slightly amend the code to the following, it is successful but I do get "None" on the console box on the right

def digit_sum(n):
    string = str(n)
    total = 0
    
    for x in string:
        total += int(x)
    return total

what could be the problem? also, how come return total gives me "None" instead of a number?


#2

a function returns None by default, if you want to return something else, you can use the return keyword, the catch is, the moment a return keyword is reached, the function ends

So, in your first code, your loop breaks in its first iteration given a return keyword is reached which means the function needs to end

I think the None is caused by the exercise, a function only executes when called. So, if you want to actually see it working, add a function call

to print what a function returns, add a print keyword before the function call


#3

A post was split to a new topic: Digit sum


#5

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