Brandon Rutledge
Brandon Rutledge

Reputation: 39

Converting numbers to binary in Python

I am trying to produce inputed values such as 5 and produce the binary version of that value and also tell how many ones and zeros there are. Does anyone know how I should go about this? And also how can I sort the output

Decimal Binary Ones Zeroes

5 101 2 1

def begin():
    str=0
    num = []

    while num != -1:

        num = int(input('Please enter some positive integers. Enter -1 to quit.\n'))

        if num > 512:
            str += 1
            num-=512
        else:
            str += 0

        if num > 256:
            str += 1
            num-=256
        else:
            str +=0

        if num > 128:
            str += 1
            num-=128
        else:
            str +=0

        if num > 64:
            str += 1
            num-=64
        else:
            str +=0

        if num > 32:
            str += 1
            num-=32
        else:
            str +=0

        if num > 16:
            str += 1
            num-=16
        else:
            str +=0

        if num > 8:
            str += 1
            num-=8
        else:
            str +=0

        if num > 4:
            str += 1
            num-=4
        else:
            str +=0

        if num > 2:
            str += 1
            num-=2
        else:
            str+=0

        if num > 1:
            str += 1
            num-=1
        else:
            str +=0

    print('Decimal Binary\t\tOnes\tZeros')
    print('--------------------------------------')
    num.sort()
    print(num)


begin()

Upvotes: 0

Views: 181

Answers (2)

wang wynn
wang wynn

Reputation: 184

There is a more simple to express:

>>>bin(5)
'0b1010'

'bin' can be used after python 2.6

Upvotes: 0

Sven Marnach
Sven Marnach

Reputation: 601809

How about

n = 5
s = format(n, "b")
print(n, s, s.count("0"), s.count("1"))

To do this in a less limited way with significantly less code?

Upvotes: 3

Related Questions