Request for help from Python beginner:
I don't want you to do the work for me, just some help to know where my mistakes are and how to correct them.
I am trying to code a program to convert any decimal number into binary. In the case of an infinitely repeating decimal number, the number should terminate at 5 significant digits.
I have nearly all of the code completed, but have encountered a couple of issues.
Here's my code:
numint = "" numfrac = "" values = "" binint = "" binfrac = "" number = raw_input("Input a number") values = number.split(".") integer = int(values) while integer >= 1: intremainder = integer % 2 integer = integer / 2 intremainder = str(intremainder) binint = binint + intremainder binint = binint[::-1] if "." in number: fraction = float(values) / (10 ** len(values)) fraction1 = float(fraction) * 2 fraction1 = str(fraction1) binfrac1 = fraction1 if "1" in binfrac1: fraction1 = float(fraction1) fraction1 - 1 binfrac1 = str(binfrac1) fraction2 = float(fraction1) * 2 fraction2 = str(fraction2) binfrac2 = fraction2 if "1" in binfrac2: fraction2 = float(fraction2) fraction2 - 1 binfrac2 = str(binfrac2) fraction3 = float(fraction2) * 2 fraction3 = str(fraction3) binfrac3 = fraction3 if "1" in binfrac3: fraction3 = float(fraction3) fraction3 - 1 binfrac3 = str(binfrac3) fraction4 = float(fraction3) * 2 fraction4 = str(fraction4) binfrac4 = fraction4 binfrac4 = str(binfrac4) if "1" in binfrac4: fraction4 = float(fraction4) fraction4 - 1 binfrac4 = str(binfrac4) fraction5 = float(fraction4) * 2 fraction5 = str(fraction5) binfrac5 = fraction5 binfrac5 = float(binfrac5) if "1" == binfrac5: fraction5 = float(fraction5) fraction5 - 1 binfrac5 = str(binfrac5) binfrac = binfrac1 + binfrac2 + binfrac3 + binfrac4 + binfrac5 print binint + "." + binfrac
Yes, my code isn't particularly elegant. I intend to shorten a lot of it with a while loop, once I get this code working.
My issues are that the if statements that would subtract 1 from the fraction value if the fraction value is greater than 1 don't work.
My second problem is that in the final converted number, I end up with multiple decimal points. I suspect this is a problem with one of my "fraction * 2" lines, but don't know what to do to correct it.