'Python function that turns a number into binary [duplicate]

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'
    else: 
        while n>0:
            x = 0
            while 2**x<n:
                x = x+1
                B.append(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



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source