I'm trying to get the function to work, it is suppose to convert Decimal to Binary but all it gives me different numbers instead. Like if I enter 12, it would give me 2. I'm not sure where in the code my issue is located. Any help would be great, thank you!
def decimalToBinary(value):
if value < 0: #Base case if number is a negative
return 'Not positive'
elif value == 0: #Base case if number is zero
return 0
else:
return decimalToBinary(value//2) + (value%2)
This may also work
def DecimalToBinary(number):
#This function uses recursion to convert & print decimal to binary number
if number > 1:
convertToBinary(number//2)
print(number % 2,end = '')
# decimal number
decimal = 34
convertToBinary(decimal)
#..........................................
#it will show output as 110100
You faced error because you adding numbers and not iterables but want to get bits sequences...,so you have to convert values you are adding to tuples or strings (or lists), see code below:
def decimalToBinary(value):
if value < 0: #Base case if number is a negative
return 'Not positive'
elif value == 0: #Base case if number is zero
return (0,)
else:
return decimalToBinary(value//2) + (value%2,)
print decimalToBinary(12)
I've replaced (value%2)
to (value%2,)
to create tuple(,
matter, for python it's mean creating a tuple, braces aren't do it... ) and return 0
to return (0,)
. However you can convert it to string too. For that replace (value%2)
to str(value%2
and 0
to str(0)
.
Note that you can use built-int bin
function ti get binary decimal:
print bin(12) # 'ob1100'
Good luck in your practice !
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With