There is no input validation for this, but that aside, I would appreciate it if anyone could help me improve the logic of this script.
import math
#Input
num = input("Enter a whole number: ")
#Floors input in case of a non whole number
decimal = math.floor(float(num))
#Variables
exp = 0
divTwo = 1
zeros = 0
total = ""
if decimal < 0:
total += str('-')
decimal = -decimal
if decimal == 0:
total = str('0')
else:
#Loops while remainder is > 0.
while int(decimal) > 0:
#Increases exponent by one if 2^exp is less than or equal to the remainder.
if 2 ** exp <= int(decimal):
exp += 1
else: #Multiplies 2 by the exponent and places zeros in between 1s. Also subtracts from the exponent.
exp -= 1
#Determines whether or not to subtract from the remainder and add a '1' to the binary translation or just add a '0' to the binary translation.
if 2 ** exp <= int(decimal):
#Counts how many zeros need to be added to the end of the binary translation.
if 2 ** exp == int(decimal):
divTwo = int(decimal)
#Loops until all remaining zeros have been accounted for.
while divTwo > 1:
divTwo = divTwo / 2
zeros += 1
decimal = int(decimal)
decimal -= 2 ** exp
total += str('1')
else:
total += str('0')
#Places remaining zeros.
while zeros > 0:
total += str('0')
zeros -= 1
#Displays answer.
print ('Binary: ' + total)
input()
#
#
#Or 'bin(decimal)' works too, but this was for fun
#
#
Here is a working version of the script.
"{0:b}".format(num)
right? \$\endgroup\$bin(x)[2:]
then? \$\endgroup\$