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.
1 Answer 1
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))
-
\$\begingroup\$ It works for the most part, however it freezes if you input 2. Everything above 2 works. Even 1 works. \$\endgroup\$Confettimaker– Confettimaker2016年07月01日 14:18:07 +00:00Commented Jul 1, 2016 at 14:18
-
\$\begingroup\$ @Confettimaker That's correct, I mistakenly at some point removed the
=
from2 ** exp <= number
. \$\endgroup\$2016年07月01日 14:31:45 +00:00Commented Jul 1, 2016 at 14:31
Explore related questions
See similar questions with these tags.
"{0:b}".format(num)
right? \$\endgroup\$bin(x)[2:]
then? \$\endgroup\$