-1

Have this print statement which correctly calculates the value of 'Count' and that is what I am returning, but eventually I am getting 'None' as a result. Please point out the correction that have to make the function provide the correct value of count...

def additive_persistence(num, count):
    sumer = 0
    num_copy = num

    while num_copy:
        sumer = sumer + (num_copy % 10)
        num_copy = num_copy // 10
    count += 1
    print(sumer, count)      # just to check the calculation is right!
    if sumer > 9:
        num = sumer
        additive_persistence(num, count)

    else:    
        return (count)

counter = 0    
number = int(input("Enter Number: "))
add_pers = additive_persistence(number, counter)
print("Additive Persistence of number {}, is: {}".format(number, add_pers))
Adarsh Namdev
  • 127
  • 1
  • 10

2 Answers2

3

You have failed to recurse properly.

  return additive_persistence(num, count)
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
0

You need to call your function and return its value in a recursive function:

   while num_copy:
        sumer = sumer + (num_copy % 10)
        num_copy = num_copy // 10
    count += 1
    print(sumer, count)      # just to check the calculation is right!
    if sumer > 9:
        num = sumer
        return additive_persistence(num, count)
Chen A.
  • 10,140
  • 3
  • 42
  • 61
  • Thanks for correcting the code.. its working now! I understood the fact that I should be returning some value too when I am calling the function again inside it! – Adarsh Namdev Oct 21 '17 at 10:10
  • Yep, that's how it works. This is called recursive function, since you call the same function from inside of it. – Chen A. Oct 21 '17 at 10:11