0

I have a very simply code looks like following:

   def divider(numberA, numberB):
       numberC = numberA%numberB

       if numberC != 0:
            divider(numberB, numberC)
       else:
            print numberB
            return numberB

   if __name__=="__main__":
       print divider(60,25)

I know I should put a return inside the numberC !=0 loop. However, if I stick to my current code (without return) I will get output like this:

5 
None

My question is why these two numbers in the output are different in values ?

Mrk421
  • 5
  • 3

1 Answers1

1

You are ignoring the return value of the recursive call:

if numberC != 0:
    divider(numberB, numberC)

You need to explicitly return that result:

if numberC != 0:
    return divider(numberB, numberC)

You see None as the return value of divider(60, 25) because your outermost call never returned anything, so the default behaviour is to return None instead.

Your code does this:

divider(60, 25)
 |  numberC = 60 % 25 = 10
 |  numberC != 0 is True:
 |      divider(25, 10)
 |       |  numberC = 25 % 10 = 5
 |       |  numberC != 0 is True:
 |       |      divider(10, 5)
 |       |       |  numberC = 10 % 5 = 0
 |       |       |  numberC != 0 is False
 |       |       |      print numberB -> "5"
 |       |       \      return numberB = 5
 |       \  function ends, return None
 \  function ends, return None
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • @Mrk421: not really, not without capturing `sys.stdout` so you can catch the string `print` writes to it, then converting that back to an integer.. – Martijn Pieters Aug 07 '15 at 18:29
  • Martijn, thanks. A further question: why the result is not None 5 but 5 None? Means why it print 5 first then None ? I would expect the main first get the return value from divider(60,25) which is None then the program run divider(25,10) and following codes. Thanks – Mrk421 Aug 07 '15 at 18:31
  • @Mrk421: no, you are printing `5` *first*, then returning that value. The rest of the stack of calls then return `None`, which is finally printed by another `print` statement. – Martijn Pieters Aug 07 '15 at 18:34