4. digit_sum


#1

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?


#2

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


#3

Why doesn't for work here though?


#4

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

for loop always has the following syntax:

for .. in ..:

#5

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.


#6

here:

while len(n) > 1:

why both to use len? you are working with numbers


#7

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


#8

By making it smaller than 10?


#9

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

#10

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


#12

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