I have a function that converts an integer to binary.
def conversion(num):
if num >= 1:
conversion(num // 2)
i = str(num % 2)
return i
num = int(input('Enter number'))
print(conversion(num))
This returns 1 which is only the first value in the actual answer
The code below gets me the answer I am looking for (101) but I want to be able to return that value instead of having the function perform the print
def conversion(num):
if num >= 1:
conversion(num // 2)
i = str(num % 2)
print(i,end=' ')
return
num = int(input('Enter number'))
conversion(num)
The only reason this prints the answer all on one line is because of the end=' '
How do I actually store the value as 101 all on one line and return it as i?
CodePudding user response:
You can notice that you have called the function inside it. That concept's name is recursion
. And every time the recursing is performed, you should save the result of that recursing step or do something with the result...
Your second funtion did that, it print out the results of every step you divide the number by two, so on the output you can see them in order.
In your first one, you forget to use the result so try to move conversion(num // 2)
to the place it should be in.
CodePudding user response:
And I'm sure you realize that PRINTING the answer is very different from RETURNING the answer. What you need to do is build up the components in a list, then join the list into a string:
def conversion(num):
answer = []
while num > 0:
answer.insert(0, str(num%2))
num = num // 2
return ''.join(answer)
num = int(input('Enter number'))
print(conversion(num))
Note that I use "insert" to add the digits in the proper order, since the higher bits have to go in the left side.