Digit Sum(what's wrong with my code?


#1



def digit_sum(n):
    n = raw_input("any number plz")
    add = []
    total = 0
    for i in n:
        add.append(n)
        for num in range(add):
            total += add[num]
            return total


#2

The return is happening on the first iteration of the loop.

Worse though, is this:

n is your function's parameter, given in the argument of the function call. That line effectively nullifies any utility this function may offer.

This is meant to be a pure function in regards to what we can expect from it. The same response for the same inputs. For that reason we would not get user input inside the function, but outside. Which input would be the argument.

def digit_sum(n):
              ^
    #      parameter
    # code
    return

print digit_sum(1234)
                 ^
              argument

More...

You have defined add as a list. It cannot be used to define a range, only its integer length may be used for that purpose.

>>> list(range([1,2,3,4,5]))
Traceback (most recent call last):
  File "<pyshell#148>", line 1, in <module>
    list(range([1,2,3,4,5]))
TypeError: 'list' object cannot be interpreted as an integer
>>>

More...

This assumes n is a string, which if it was raw input would be, but we may for the time expect n to be an integer. Integers are not iterable. What's more is you are appending the whole number each time, not just the digit.

for i in str(n):

Now i will be the string representation of a single digit, which may now be cast back to integer and accumulated to the running total. No appending to any list needed.

This can be done with way less logic that you have here.


#3

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