1

I am writing a function to convert from decimal to binary system to practice recursion (not for school, uni, or the like!).

def toBin(n):
    a = ''
    if n <= 1:
       return n
   else:
   if n > 1:
       toBin(n//2)
       b = (n % 2)
       b = str(b)
       a = a+b
       print(a)
       return a

print(toBin(99))

Why won't the function return '100011' but only its last digit ('1')?

  • In case you're looking for a practical solution (and not just debugging) you can just define the function as: ``to_bin =lambda x: "{0:b}".format(x)`` https://stackoverflow.com/questions/699866/python-int-to-binary – Dimgold Mar 13 '18 at 12:25
  • `toBin(n//2)` <- What's that supposed to do? You call `toBin` and then you throw its return value away. – Aran-Fey Mar 13 '18 at 12:28
  • @Aran-Fey : the idea was to first divide the number by 2 and then take the residual from that (0 or 1) and use this to build the concatenated string. – Johannes Schwaninger Mar 13 '18 at 12:34
  • 1
    you have 2 bugs in the code - one is that ``return n`` should return a string and the second is that you need to assign the result of the internal to bin to a: ``a= toBin(n//2)`` – Dimgold Mar 13 '18 at 12:36
  • @Dimgold: Thanks so much! That solved it. – Johannes Schwaninger Mar 13 '18 at 12:49

0 Answers0