Any ideas how I could improve this? I already know that there is no checking for anything other than a 1
, so you can enter a 2
or an a
or a b
and it will be interpreted as a 0
, not interfering with the program's functionality. What I would like to know is if anyone has any suggestions for improving the logic.
def main():
#Input
binary = input("Enter a line of binary: ")
#Reverses input
toCalc = binary[::-1]
#Finds length of input
binLen = len(binary)
#Variables
total = 0
exp = 0 #Exponent
#loop while current character place is less than input length
while exp < binLen:
if toCalc[exp] == "1": #If current char is a '1', add 2^exp to the total
total += 2 ** int(exp)
exp += 1
print (total)
main()
main()
Here is a link to a working version of the script.