Binary Function

How can I improve this:

def binary(num):
    binary_num = int(bin(num).strip("0b"))

  except TypeError:
    message = f"Please enter a number for the binary function not a {str(type(num)).strip('<').strip('class').strip('>')}."
    yield None
    yield message

    message = "Successfully converted number to binary."
    yield binary_num
    yield message

for num in binary({1, 2, 3}):


Depends on your goal. If you want to write something that simulates the binary method it’s interesting to do it mathematically (also allowing for decimal places!).

If it’s just to parse, I would personally just have the function return the string value (no need for a message unless it’s an error).

I don’t see the point of turning the binary sequence into an int as it limits what you can do to it. (Assuming you want to do boolean algebra on the number). Note that there are bitwise operators built-in (Bitwise Operators in Python – Real Python). Which if you’re building methods to duplicate the behaviour can be good testing models.


>>> 4 | 1 # 100 OR 001
>>> 4 & 1 # 100 AND 001
>>> ~4 # NOT 100 # note this flips to 011, but also all the leading 0's turn to 1
# in signed 2's complement this is indeed -5
>>> 4 << 2 #shift right by 2, (virtually multiplies by 2^shift)
1 Like

We know you meant, shift left; pretty sure.

1 Like

I still don’t know my left from my right!

1 Like

Yeah, I never know how to answer, “is that your left, or my left?”


Going to be helpful. Thank you for the article. I’m going to read it.
It’s so long!!! :open_mouth: :open_mouth: :open_mouth:
I put it in a google document which is 79 pages long. I decide to print it double sided, black and white, 2 pages a sheet, which means I reduce the pages by a factor of 4(takes 20 pages).