-1

This will be really funny... Given following python codes:

def getBinary(binaryInput, kSize, beginBit):
    if int(binaryInput[beginBit + kSize-1])==1:
        print 'entered!!!'
        shortE = binaryInput[beginBit:kSize+beginBit]
        print 'shortE is now: ', shortE
        print 'kSize is now: ', kSize
        return (shortE,kSize)
    else :
        print 'else entered...'
        kSize -=1
        getBinary(binaryInput, kSize, beginBit)

result = getBinary("{0:b}".format(6), 3, 0)
print result

The output is:

else entered...
entered!!!
shortE is now:  11
kSize is now:  2
None

I mean since shortE is 11 and kSize is 2, why the return value is None?

Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119
chrisTina
  • 2,298
  • 9
  • 40
  • 74
  • possible duplicate of [Python recursion with list returns None](http://stackoverflow.com/questions/2599149/python-recursion-with-list-returns-none) – Peter Wood Feb 18 '15 at 08:28
  • Why people like finding `duplicate` so much? @PeterWood – chrisTina Feb 18 '15 at 13:26
  • @Liquid Because it is helpful to everybody. Including, and especially, you. – David Heffernan Feb 18 '15 at 19:54
  • @Liquid Because I saw someone ask exactly the same question the other day, and it had been asked 5 years ago. This place is great as a resource for others because of the density of good answers to specific questions. You're watering it down; I'm trying to thicken it. – Peter Wood Feb 18 '15 at 21:19
  • Does this answer your question? [Why does my recursive function return None?](https://stackoverflow.com/questions/17778372/why-does-my-recursive-function-return-none) – VLAZ Nov 03 '22 at 18:02

2 Answers2

2

When a function ends without executing a return statement, it returns None. Instead of

getBinary(binaryInput, kSize, beginBit)

you mean

return getBinary(binaryInput, kSize, beginBit)
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • 1
    But why it does not executing `return`? From the console output, I can tell that the in the second time, the function go into the `if` statement and calculate the value of `shortE` and `keySize`, and then it should go to the `return` statement and return the according value, right? – chrisTina Feb 18 '15 at 19:50
  • The else is entered on the outer most call, and that's the one that returns and assigns to `result`. – David Heffernan Feb 18 '15 at 19:52
1

The code is missing in the else part:

def getBinary(binaryInput, kSize, beginBit):
    if int(binaryInput[beginBit + kSize-1])==1:
        print 'entered!!!'
        shortE = binaryInput[beginBit:kSize+beginBit]
        print 'shortE is now: ', shortE
        print 'kSize is now: ', kSize
        return (shortE,kSize)
    else :
        print 'else entered...'
        kSize -=1
        return getBinary(binaryInput, kSize, beginBit)
        # ^^^^
falsetru
  • 357,413
  • 63
  • 732
  • 636