You get that error because you read a string with input
but immediately convert it to an int:
bits=int(input("enter an 8-bit binary number"))
--- there!
An input such as "00110011"
gets stored into bits
as the decimal value 110011
, without the leading zeroes. And as the error says, an int
has no len
.
Remove the cast to int
to make that part work. But there are lots of additional errors in your (original) code – I hope I got them all. (Pardon the exclamation marks, but all of your mistakes warranted at least one.)
Your original code was
bits=int(input("enter an 8-bit binary number"))
for i in range (0,8):
if bits >8 and bits <8:
print("must enter an 8 bit number")
if input >1:
print("must enter a 1 or 0")
else:
rem=bits%10
sum=((2**i)*rem)
bits = int(bits/10)
print(sum)
adjusted to
bits=input("enter an 8-bit binary number")
sum = 0 # initialize variables first!
if len(bits) != 8: # test before the loop!
print("must enter an 8 bit number")
else:
for i in range (8): # default start is already '0'!
# if i > 1: # not 'input'! also, i is not the input!
if bits[i] < '0' or bits[i] > '1': # better also test for '0'
print("must enter a 1 or 0")
# else: only add when the input value is '1'
elif bits[i] == '1':
# rem = bits%10 # you are not dealing with a decimal value!
# sum = ((2**i)*rem) # ADD the previous value!
sum += 2**i
# bits = int(bits/10) # again, this is for a decimal input
# mind your indentation, this does NOT go inside the loop
print(sum)