0

我在编写程序的地方有点卡住了。我的非二进制输入例外似乎不起作用。我在运行程序时收到此错误消息,“如果 [i == '0' 或 i == '1' for i in bin2dec] 为 False]:TypeError: 'int' object is not iterable”。如果有人可以帮忙。

e1=True
print"Welcome to CJ's Program V1.00.8\n"
    while e1:
        try:
            bininput= int(input("Please enter a binary number: "))
            e1=False
        except NameError: 
            print"Please try again.\n"
            time.sleep(0.5)
        except SyntaxError: 
            print"Please try again.\n"
            time.sleep(0.5)

    if False in [i == '0' or i == '1' for i in bininput]:
        print "\nIts not Binary number. Please try again."
        time.sleep(1)
    else:
        print "\nIts a Binary number!\n" 

        decnum = 0 
        for i in bininput: 
            decnum = decnum * 2 + int(i)
            time.sleep(0.25)
        print decnum, "<<This is your answer.\n"
4

1 回答 1

0

与字符串不同,您不能像人们所说的那样循环遍历整数中的每个数字/字符 - 这就是它的意思。

对此的最简单的解决方案是通过每次将 int 转换为字符串来将其作为字符串进行迭代。

e1=True
print"Welcome to CJ's Program V1.00.8\n"
while e1:
    try:
        bininput= int(input("Please enter a binary number: "))
        e1=False
    except NameError: 
        print"Please try again.\n"
        time.sleep(0.5)
    except SyntaxError: 
        print"Please try again.\n"
        time.sleep(0.5)

if False in [i == '0' or i == '1' for i in str(bininput)]:
    print "\nIts not Binary number. Please try again."
    time.sleep(1)
else:
    print "\nIts a Binary number!\n" 

    decnum = 0 
    for i in str(bininput): 
        decnum = decnum * 2 + int(i)
        #time.sleep(0.25)
    print decnum, "<<This is your answer.\n"
于 2013-09-15T17:01:10.270 回答