4. digit_sum


So, I'm trying to use a for loop to increment a variable I created called sum with the last digit of the input, then dividing the input by 10 until there's only one digit, then adding it to sum.
Here's my code:

def digit_sum(n):
    sum = 0
    for len(n) > 1:
        num = n - int(n/10)*10
        sum += num
        n = int(n/10)
    return sum

However, it always gives me the following mistake:

  File "python", line 3
    for len(n) > 1:
SyntaxError: invalid syntax

What's wrong with my code?


what you are trying to achieve here requires a while loop, not a for loop


Why doesn't for work here though?


because a for loop is to loop over a list, tuple or dictionary.

for loop always has the following syntax:

for .. in ..:


Also, I substituted for for while and got this error now:

Oops, try again. Does your digit_sum function take exactly one argument (a positive integer)? Your code threw a "object of type 'int' has no len()" error.

What can I do to reverse this? Tried making n float but it didn't work.



while len(n) > 1:

why both to use len? you are working with numbers


How else could I make it stop when there is only one digit on n?


By making it smaller than 10?


Now I get it, thank you for the information!
My code is now:

def digit_sum(n):
    sum = 0
    while n > 9:
        num = n - int(n/10)*10
        sum += num
        n = int(n/10)
    sum += n
    return sum


very good, by reaching this conclusion yourself, i hope it gave you more insight (rather then me just telling you the answer)


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