[SOLVED] Python function that turns a number into binary


I know that in python there are certain functions like bin that turn
decimal numbers into binary numbers. I would like to build one myself. I have tried the following:

def binary(n):
    bina = ''
    B = []
    if n == 0:
        bina = '0'
        while n>0:
            x = 0
            while 2**x<n:
                x = x+1
                n = n-2**(x-1)

The problem is that when I have the exponents with base 2 in the array B I don’t know how to actually read them so that I obtain the actual binary number made of ones and zeroes. How can I make the code above work?

before someone says that my question was already asked, my question is how can I make the code above work, not starting over and trying another method


def make_binary(num):
    binary = ''
    while num > 0:
        binary = str(num % 2) + binary
        num = num // 2
    return binary

Answered By – Parvesh Kumar

Answer Checked By – Mildred Charles (BugsFixing Admin)

Leave a Reply

Your email address will not be published.