Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python code to convert Integer into Binary

I need a code in Python 3.3 to convert an integer into binary. This is my first try:

a = input(str("Please Enter a Number")
if a == float:
    print (1)
else print(0)
b = a/2
while True:
    if b == float:
        print(1)
    else print(0)

I don't know why I keep getting errors with the if a == float:. And I know that the rest of the code is wrong too, but this : makes me crazy.

like image 374
John Smith88 Avatar asked Aug 04 '26 23:08

John Smith88


2 Answers

Your code has a lot of issues:

  1. Your indentation is off. Indentation is very important in Python since that is how it knows what goes with what.
  2. You need to use isinstance to see if an object is a float. I assume this is what you are trying to do with a == float. But, that doesn't make sense because, in Python 3.x., input always returns a string object. So, a is a string. However, if float is actually a variable, then you should change its name. Naming a variable float is a bad practice since it overrides the built-in.
  3. You are missing a colon at the end of each else.
  4. You are missing a closing parenthesis on the first line.
  5. The str in the first line is unnecessary (not an error, but I just thought I'd mention it).

However, instead of fixing all this, I'm going to introduce you to the bin built-in:

>>> n = 127
>>> bin(n)
>>> # The "0b" at the start means "binary".
'0b1111111'
>>> # This gets rid of the "0b"
>>> bin(n)[2:]
'1111111'
>>>

It was built explicitly to do what you are trying to do.

Also, here are some references on Python you might enjoy:

http://www.tutorialspoint.com/python/python_overview.htm

http://wiki.python.org/moin/BeginnersGuide/Programmers

You can just use the bin function:

>>> bin(100)
'0b1100100'

Ignore the 0b infront of the string. You can always get the raw binary numbers using using bin(your_numer)[2:].

Also, you can get this using the format function:

>>> format(100, 'b')
'1100100'
like image 26
Games Brainiac Avatar answered Aug 06 '26 12:08

Games Brainiac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!