Python二进制输入异常不起作用

时间:2013-09-15 15:52:28

标签: python python-2.7

我对程序进行编码时有点困惑。我没有bianry输入的例外似乎不起作用。我在运行程序时收到此错误消息,“如果在[i =='0'中为False,或者在bin2dec中i为i =='1'时出现错误:TypeError:'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 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"

1 个答案:

答案 0 :(得分: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"