Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
An algorithm
#1
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)
Reply
#2
Please use code tags
Reply
#3
And do you have a question? I note that you are not handling invalid input as per the requirements.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#4
Any reason you can't use "bin(n)" in your def?
If it ain't broke, I just haven't gotten to it yet.
OS: Windows 10, openSuse 42.3, freeBSD 11, Raspian "Stretch"
Python 3.6.5, IDE: PyCharm 2018 Community Edition
Reply
#5
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.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020