Sum_Digit Question About Preference


#1



total_sum = []

def digit_sum(n):
    for a in str(n):
        total_sum.append(int(a))
    print total_sum
    return sum(total_sum) 

#why is the code below more preferable than the code above?

def digit_sum(n):
    total = []
    for a in str(n):
        total.append(int(a))
    print total
    return sum(total)


#2

The second example is correct. total should be initialized inside the function so the value is always reset to 0 with each run.

Edit

As an aside, total could be a number and then a data structure would not be needed.

total = 0
# ...
    total += int(a)

return total

Also, remove your debugging print statement so the function has no output but a return. If a function has a return value the time to print, most often is back at the caller.

print digit_sum(1234567)
      ------------------
            caller

#3

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