Hello trying to learn python and decided to write a small program that will convert 8 digit binary numbers to base 10. Now I know python has a built in function for this and there are a few other ways of doing this but Im trying to figure out what is going wrong in my solution.
What I'm trying to achieve is the program goes through the string and checks for a 1 if it finds a 1 then it will add the corresponding value for that index to the total. My code just works if there is only a single 1 in the string but as soon as the is more than 1 it will add 128 for every 1.
Anyone able to point out where I'm going wrong?
Code:
output = 0
data = input("Enter a binary number:")
print (len(data))
print (type(data))
if len(data) < 8 or data.isalpha(): #need to add check for digits that are not 0 or 1
print("A binary number must be 8 digits long and contain only 1's and 0's")
for digit in data:
if digit == "1":
if data.index(digit) == (0):
output = output+128
elif data.index(digit) == (1):
output = output+64
elif data.index(digit) == (2):
output = output+32
elif data.index(digit) == (3):
output = output+16
elif data.index(digit) == (4):
output = output+8
elif data.index(digit) == (5):
output = output+4
elif data.index(digit) == (6):
output = output+2
elif data.index(digit) == (7):
output = output+1
print(output)
What I'm trying to achieve is the program goes through the string and checks for a 1 if it finds a 1 then it will add the corresponding value for that index to the total. My code just works if there is only a single 1 in the string but as soon as the is more than 1 it will add 128 for every 1.
Anyone able to point out where I'm going wrong?