TransWikia.com

Adding up digits of an input number with recursion in Python

Stack Overflow Asked by indian_trash on February 11, 2021

So I am trying to add up the digits of an inputted number with Python using code. I have to use recursion or else my professor won’t except it. And I have been running into issues constantly. The most infuriating one, however, is when the output says "None" for the sum of the inputted integer.

Here is my code:

def run():
  inputNum = int(input("Enter an int: "))
  print(f"sum of digits of {inputNum} is {digit_sum(inputNum)}.")

def digit_sum(inputNum):
  if (inputNum < 10):
    return inputNum
  elif (inputNum >= 10):
    inputNum = inputNum % 10
    digit_sum(inputNum / 10)
  
if __name__ == "__main__":
  run()

Whenever I input any integer, except for a single-digit one, it says "The sum of the digits of {inputted number} is None". And I have no idea why. I would really appreciate it if someone could help me on this.

5 Answers

There are at least two mistakes in your code:

inputNum = inputNum % 10
digit_sum(inputNum / 10)

First, you're changing the value of inputNum when you still need that value in the next statement. Second, you're making a common recursion beginner's error in that if your function returns a value, you need to deal with that returned value when you call your function recursively. A working version of your code might read:

def digit_sum(inputNum):
    if inputNum < 10:
        return inputNum
    
    return inputNum % 10 + digit_sum(inputNum // 10)

We could also implement a different approach using the often forgotten divmod function:

def digit_sum(number):
    if number < 10:
        return number

    quotient, remainder = divmod(number, 10)
    return remainder + digit_sum(quotient)

There are two similar recursive digit summing problems that turn up on SO. One simply sums the digits. The other keeps reapplying the summing logic until the result boils down to a single digit. Providing example input and output with your quesion can help clarify which algorithm you're implementing.

Answered by cdlane on February 11, 2021

This can be done simply with while loop like this,

def digit_sum(inputNum):
    result = 0
    while len(str(inputNum)) > 1:
        result += inputNum % 10
        inputNum //= 10
    return inputNum + result 

If you are only comfortable with recursion, try this.

def digit_sum(inputNum, result=0):
    if inputNum >= 10:
        result = inputNum % 10
        inputNum //= 10
        return result + digit_sum(inputNum, result)
    else:
        return inputNum

Answered by Maran Sowthri on February 11, 2021

I found several issues:

  • elif could be replaced with else
  • return requires in else section
  • else logic is incorrect

Here is corrected code:

def run():
    input_num = int(input("Enter an int: "))
    print(f"sum of digits of {input_num} is {digit_sum(input_num)}.")


def digit_sum(input_num):
    if input_num < 10:
        return input_num
    else:
        return int(input_num % 10) + digit_sum(int(input_num/10))


if __name__ == "__main__":
    run()

Sample output:

Enter an int: 678
sum of digits of 678 is 21.

Answered by Alderven on February 11, 2021

Check the below code it's easy hopefully it will help

    def run():
       num = int(input("Enter an int: "))
       result = sum_of_digit(num) 
       print("Sum of digits in",num,"is", result) 

    def sum_of_digit( n ): 
       if n == 0: 
          return 0
       return (n % 10 + sum_of_digit(int(n / 10))) 




    if __name__ == "__main__":
        run()

Answered by Arijeet Mukherjee on February 11, 2021

As Green Cloak Guy says you are not returning any value in your elif statement. Therefore you will be getting a "None" result.

Also looking at your code it will only return a single value based on the initial value divided by ten. You may want to try:

retNum = inputNum % 10
baseNum = inputNum - retNum
return retNum + digit_sum(baseNum/10)

This will add the modulo value to whatever is returned by the recursion method. Hope I have been able to help

Answered by lachlan on February 11, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP