使用 len() 函数

我不断收到错误对象类型 int has no 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")


慕虎7371278
浏览 242回答 2
2回答

慕莱坞森

您收到该错误是因为您读取了一个字符串,input但立即将其转换为 int:bits=int(input("enter an 8-bit binary number"))&nbsp; &nbsp; &nbsp;--- there!输入如"00110011"被存储bits为十进制值110011,没有前导零。正如错误所说, anint没有len.移除演员表以int使该部分工作。但是在您的(原始)代码中还有很多额外的错误——我希望我都知道了。(请原谅感叹号,但你所有的错误都至少有一个。)你的原始代码是bits=int(input("enter an 8-bit binary number"))for i in range (0,8):&nbsp; &nbsp; if bits >8 and bits <8:&nbsp; &nbsp; &nbsp; &nbsp; print("must enter an 8 bit number")&nbsp; &nbsp; if input >1:&nbsp; &nbsp; &nbsp; &nbsp; print("must enter a 1 or 0")&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;rem=bits%10&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;sum=((2**i)*rem)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;bits = int(bits/10)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;print(sum)调整为bits=input("enter an 8-bit binary number")sum = 0 # initialize variables first!if len(bits) != 8:&nbsp; # test before the loop!&nbsp; &nbsp; print("must enter an 8 bit number")else:&nbsp; &nbsp; for i in range (8): # default start is already '0'!&nbsp; &nbsp; &nbsp; &nbsp; # if i > 1: # not 'input'! also, i is not the input!&nbsp; &nbsp; &nbsp; &nbsp; if bits[i] < '0' or bits[i] > '1':&nbsp; # better also test for '0'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print("must enter a 1 or 0")&nbsp; &nbsp; &nbsp; &nbsp; # else: only add when the input value is '1'&nbsp; &nbsp; &nbsp; &nbsp; elif bits[i] == '1':&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # rem = bits%10&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# you are not dealing with a decimal value!&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # sum = ((2**i)*rem)&nbsp; &nbsp; # ADD the previous value!&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sum += 2**i&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # bits = int(bits/10)&nbsp; &nbsp;# again, this is for a decimal input&nbsp; &nbsp; # mind your indentation, this does NOT go inside the loop&nbsp; &nbsp; print(sum)

ABOUTYOU

这应该很容易,因为python的“int”接受“base”参数,它告诉它使用哪个数字基数strbin = input('enter bin value\n')converted = int(strbin,base=2)print('base 2 converted to base 10 is: ', converted)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python