我不断收到错误对象类型 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")) --- there!输入如"00110011"被存储bits为十进制值110011,没有前导零。正如错误所说, anint没有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)
这应该很容易,因为python的“int”接受“base”参数,它告诉它使用哪个数字基数strbin = input('enter bin value\n')converted = int(strbin,base=2)print('base 2 converted to base 10 is: ', converted)