4/15


#1

def digit_sum(n):
if n < 100:
ones = n % 10
tens = n // 10
print ones + tens
elif n > 99 and n < 1000:
ones = n % 10
tens = n % 100 // 10
hundreds = n // 100
print ones + tens + hundreds

digit_sum(434)

I got it to return 11 but says Oops, try again. Your function fails on digit_sum(434). It returns None when it should return 11.


#2

If you are going to sum up the digits using that method you do not need to have so much code.

def digit_sum(number):
    total = 0
    while number > 0:
        total += number % 10
        number = number / 10 # Use the correct version or use floor from math
    return total

With Floor

from math import floor
def digit_sum(number):
    total = 0
    while number > 0:
        total += number % 10
        number = floor(number / 10)
    return total

There ya are, a nice and neat one. You can condense it even more and you can also use recursion and a few other methods too.


#3

Thank you. It took me a second to understand. Thanks for the help!