-3

i keep getting the error object type int has no len() not sure why. I just learned about the len function so an explanation of why its doing this would be great thanks

bits=int(input("enter an 8-bit binary number"))

for i in range (0,8):
    if len(bits) >8 or len(bits) <8:
        print("must enter an 8 bit number")
  • 1
    These are two separate problems. The first one is [this](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response), the second one is [this](https://stackoverflow.com/questions/8928240/convert-base-2-binary-number-string-to-int). – timgeb Nov 10 '18 at 22:32
  • 1
    `if bits >8 and bits <8:` will never be true because it's impossible for `bits` to be both > 8 **`and`** be < 8 (or any other value for that matter) at the same time. – martineau Nov 10 '18 at 22:34

2 Answers2

0

that should be easy, because python's "int" accepts "base" param which tells it which numeric base to use

strbin = input('enter bin value\n')
converted = int(strbin,base=2)
print('base 2 converted to base 10 is: ', converted)
0

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)
Jongware
  • 22,200
  • 8
  • 54
  • 100