小编Ray*_*ruz的帖子

如何检查输入是否为二进制格式(1和0)?

我已经制作了一个程序,但是如果用户输入不是二进制格式,我想添加一个例外.我已经多次尝试添加异常,但我似乎无法让它工作.以下是程序代码.如果有人可以帮忙,我将不胜感激.

import time
error=True
n=0
while n!=1:
    print"***Welcome to the Bin2Dec Converter.***\n"
    while error:
        try:
            bin2dec =raw_input("Please enter a binary number: ")
            error=False
        except NameError: 
            print"Enter a Binary number. Please try again.\n"
            time.sleep(0.5)
        except SyntaxError: 
            print"Enter a Binary number. Please try again.\n"
            time.sleep(0.5)


        #converts bin2dec
        decnum = 0 
        for i in bin2dec: 
            decnum = decnum * 2 + int(i)
            time.sleep(0.25)
        print decnum, "<<This is your answer.\n" #prints output
Run Code Online (Sandbox Code Playgroud)

python python-2.7

5
推荐指数
4
解决办法
1万
查看次数

标签 统计

python ×1

python-2.7 ×1