You can remove half of you code.
You need the variablesexp
,total
anddecimal
. The rest are just noise.You should remove all the
int(decimal)
s,decimal
is only ever subtracted from, and so it's not going to become a float. And so these are not needed.
You can remove all the code in
if 2 ** exp == int(decimal):
, instead just useexp
as you dozeros
.You should split your while loop so that it only does one thing at a time. You want an int
log
and then a while loop that converts the input to binary.You can replace
while zeros > 0:
with Pythons way to duplicate strings.0 * zeros
.You should make this a function.
This leads to code like:
def binary(number): # 4
output = ''
if number < 0:
output = '-'
number = -number
exp = 1
while 2 ** exp <<= number: # 2
exp += 1
while number > 0:
exp -= 1
if 2 ** exp <= number:
number -= 2 ** exp
output += '1'
else:
output += '0'
return output + '0' * exp # 1, 3
number = int(input("Enter a whole number: "))
print('Binary: ' + binary(number))