使用len()函数

时间:2018-11-10 22:28:07

标签: python

我一直在获取错误对象类型int没有len(),不确定原因。我刚刚了解了len函数,因此非常感谢为什么这样做。

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")

2 个答案:

答案 0 :(得分:0)

那应该很容易,因为python的“ int”接受了告诉它的“ base”参数 使用哪个数字基数

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

答案 1 :(得分:0)

您收到该错误是因为您使用input读取了一个字符串,但立即将其转换为int:

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

诸如"00110011"之类的输入将作为十进制值bits存储在110011中,而没有前导零。正如错误所言,int没有len

将演员表移至int,以使该部分正常工作。但是,您的(原始)代码中还有很多错误–我希望我能全部解决。 (原谅感叹号,但您的所有错误都应至少引起一个错误。)

您的原始代码是

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)

调整为

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)