I am new in Python and trying to write a binary-to-decimal converted function like below
def decimaltobinary(n):
if n > 1:
decimaltobinary(n//2)
print(n%2,end='')
#return n%2
decimaltobinary(4)
This works perfectly fine. Now the question is when I am modifying it as below, it doesn't give me correct result -
def decimaltobinary(n):
if n > 1:
decimaltobinary(n//2)
#print(n%2,end='')
return n%2
a=decimaltobinary(4)
print(a)
Am I missing something with the return statement? Any pointer will be very helpful.
CodePudding user response:
In the second example returned value from decimaltobinary
in if
is completely ignored.
What you need to do is assign the returned value to a variable and then return it together with n%2
.
Try this:
def decimaltobinary(n):
x = ''
if n > 1:
x = decimaltobinary(n//2)
#print(n%2,end='')
return str(x) '' str(n%2)
a=decimaltobinary(4)
print(a)
CodePudding user response:
You need to be careful with your return statements. Try this:
def decimaltobinary(n):
def _dtb(n, lst):
if n <= 0:
return lst
lst.append(n&1)
return _dtb(n>>1, lst)
return ''.join(map(str, reversed(_dtb(n, list()))))
print(decimaltobinary(19))
Output:
10011