0

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()
1
  • 1
    The numbers in the series from 512 down to 1 has a mathematical relationship that you can use in a for loop, instead of doing each number separately. Commented Dec 12, 2011 at 22:24

2 Answers 2

3

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?

Sign up to request clarification or add additional context in comments.

Comments

0

There is a more simple to express:

>>>bin(5)
'0b1010'

'bin' can be used after python 2.6

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.