1

I am trying to create a decimal to binary converter. The user inputs their value, and the amount is divided by two each time and added to the invertedbinary list. The amount is then converted back into an integer, to be divided by two again and so on.

value = int(input("Please enter the decimal value to be converted to binary."))
    invertedbinary = []
    while value >= 1:
        value = (value/2)
        invertedbinary.append(value)
        value = int(value)
        print (invertedbinary)
    for n,i in enumerate(invertedbinary):
        if i == isinstance(invertedbinary,int):
            invertedbinary[n]=0
        else:
            invertedbinary[n]=1
    print (invertedbinary)

Let's say I input the number seventeen. This is the output:

[8.5]
[8.5, 4.0]
[8.5, 4.0, 2.0]
[8.5, 4.0, 2.0, 1.0]
[8.5, 4.0, 2.0, 1.0, 0.5]
[1, 1, 1, 1, 1]

So we can tell that from the last line of ones, my isinstance attempt did not work. What I want to be able to do, is that if the amount is anynumber.5 then to display it as a 1, and if it is a whole number to display as a zero. So what it should look like is [1, 0, 0, 0, 1]. Ones for each float value, and zeroes for the integers.

What can I use instead of is instance to achieve this?

For anyone wondering, I've called it invertedbinary because when printed invertedbinary needs to be flipped around and then printed as a string to display the correct binary value.

4
  • I changed this to python-3.x as this requires int / int gives float behaviour; see this question. Commented Oct 23, 2016 at 23:36
  • You don't want i == isinstance(invertedBinary,int) you just want isinstance(invertedBinary,int) I'm pretty sure... Commented Oct 23, 2016 at 23:55
  • Although, not actually in this case, because you care if the number is a whole number, not an int type necessarily. Commented Oct 23, 2016 at 23:57
  • Anyway, in this case you should be using the modulus operator: % Commented Oct 24, 2016 at 0:09

1 Answer 1

1

You can always check wether the round value is equal to the value...

if (round(x) == x):
    # x is int
else:
    # x is float/double
Sign up to request clarification or add additional context in comments.

7 Comments

Wow! Thanks so much for that. It's now working as intended!
@AugustWilliams Sometimes, old and obvious works best ;-)
@KenY-N What's the problem with 8.49999999999999999?
I am fairly new to Python so I don't understand the example you have provided @KenY-N . However, in this specific program the floats will always be .5.
@KenY-N But that wasn't the condition. round(8.4999999) == 8.499999 is False, so it won't be treated as an int value
|

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.