Adding the digits of an int and Python
Question: 
    import sys
    
    def keepsumming(number):
        numberlist = []
        for digit in str(number):
            numberlist.append(int(digit))
        total = reduce(add, numberlist)
        if total > 9:
            keepsumming(total)
        if total <= 9:
            return total
    
    def add(x,y):
        return x+y
    
    keepsumming(sys.argv[1])
    

I want to create a function that adds the individual digits of any number, and
to keep summing digits until the result is only one digit. (e.g. 1048576 =
1+0+4+8+5+7+6 = 31 = 3+1 = 4). The function seems to work in some laces but
not in others. for example:

    
    
    $python csp39.py 29
    

returns None, but:

    
    
    $python csp39.py 30
    

returns 3, as it should...

Any help would be appreciated!


Answer: As others have mentioned, the problem seems to be with the part

    
    
    if total > 9:
        keepsumming(total)  # you need return here!
    

Just for completeness, I want to present you some examples how this task could
be solved a bit more elegantly (if you are interested). The first also uses
strings:

    
    
    while number >= 10:
      number = sum(int(c) for c in str(number))
    

The second uses modulo so that no string operations are needed at all (which
should be quite a lot faster):

    
    
    while number >= 10:
      total = 0
      while number:
        number, digit = divmod(number, 10)
        total += digit
      number = total
    

You can also use an iterator if you want to do different things with the
digits:

    
    
    def digits(number, base = 10):
      while number:
        yield number % base
        number //= base
    
    number = 12345
    
    # sum digits
    print sum(digits(number))
    # multiply digits
    from operator import mul
    print reduce(mul, digits(number), 1)
    

This last one is very nice and idiomatic Python, IMHO. You can use it to
implement your original function:

    
    
    def keepsumming(number, base = 10):
      if number < base:
        return number
      return keepsumming(sum(digits(number, base)), base)
    

Or iteratively:

    
    
    def keepsumming(number, base = 10):
      while number >= base:
        number = sum(digits(number, base))
    

**UPDATE:** Thanks to Karl Knechtel for the hint that this actually is a very
trivial problem. It can be solved in one line if the underlying mathematics
are exploited properly:

    
    
    def keepsumming(number, base = 10):
      return 1 + (number - 1) % (b - 1)
    

