Python Forum

Full Version: An algorithm
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hey all once again how would you create a function called
binary_converter
. Inside the function, implement an algorithm to convert decimal numbers between
0 and 255
to their binary equivalents.
For any invalid input, return string Invalid input
Example: For number 5 return string
101

i may have found a possible solution
def convertToBinary(n):
  """Function to print binary number
  for the input decimal using recursion"""
  if n > 1:
      convertToBinary(n//2)
  print(n % 2,end = '')

# decimal number
dec = 34

convertToBinary(dec)
Please use code tags
And do you have a question? I note that you are not handling invalid input as per the requirements.
Any reason you can't use "bin(n)" in your def?
If you're supposed to return something, then you shouldn't be printing anything within the function. Also, you didn't give it the name you should have. Your professor would be disappointed.