Digit Sum - Is this the correct way?


#1



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


def digit_sum(n):
    to_string = str(n)
    to_list = list(to_string)
    total = 0
    for i in to_list:
        total = total + int(i)
    return total


#2

Yes, this is correct.

But it will give an error SyntaxError: invalid token on using any number starting with 0's just like (02323,00323,0235459, etc.)


#3

What could be a good way to do this code alternatively.


#4

Perhaps try following this template:

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

#5

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