Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3 Recursivley Sum Digits of an Integer

I need help implementing a function that will take the digits of an integer and sum them together. As long as the sumDigits function implements recursion, it is valid, and the main function must be left as is. I will include a template below:

def sumdigits(value): 
    #recursively sum digits 

def main():
    number=int(input(“Enter a number :  ”))
    print(sumdigits(number))

main()

Thank you

like image 601
pythonhack Avatar asked Jan 19 '26 02:01

pythonhack


1 Answers

A very short version:

def sumdigits(value):
    return value and (value % 10 + sumdigits(value // 10))

The value and part makes it return zero rather than recurse infinitely once it gets past the last digit.

The value % 10 part gets the last digit (the "ones" place).

The sumdigits(value // 10) gets the sum of all of the digits except the last digit

// is integer division, throwing away the fractional part of the result for you automatically.

like image 83
agf Avatar answered Jan 21 '26 17:01

agf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!