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

时间:2013-09-15 11:51:25

标签: python python-2.7

我制作了一个程序,但是如果用户输入不是二进制格式,我想添加一个例外。我曾多次尝试添加例外,但我似乎无法让它发挥作用。以下是程序代码。如果有人可以提供帮助,我将不胜感激。

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

8 个答案:

答案 0 :(得分:9)

最好请求原谅。尝试使用int(value, 2)将其转换为整数:

while True:
    try:
        decnum = int(raw_input("Please enter a binary number: "), 2)
    except ValueError:
        print "Enter a Binary number. Please try again.\n"
    else:
        break

print decnum

答案 1 :(得分:6)

如果输入不是二进制格式,

int(bin2dec, 2)将抛出ValueError。但当然这可以解决你的整个问题。

答案 2 :(得分:5)

使用set()

def is_binary(x):
    return set(input_string) <= set('01')

input_string = "0110110101"
print(is_binary(input_string))

input_string = "00220102"
print(is_binary(input_string))

答案 3 :(得分:2)

使用all

>>> b = '01011'
>>> all(c in '01' for c in b) # OR  c in ('0', '1')
True
>>> b = '21011'
>>> all(c in '01' for c in b) # OR  c in ('0', '1')
False

答案 4 :(得分:2)

执行此操作的正确方法(即,如果这不是一项愚蠢的家庭作业练习)是使用int(your_string, 2)并捕获ValueError,如果字符串包含无效字符,则会引发{{1}}。

http://docs.python.org/2/library/functions.html#int

答案 5 :(得分:1)

>>> b = '01011'
>>> not(b.translate(None, '01'))
True
>>> b = '21011'
>>> not(b.translate(None, '01'))
False

答案 6 :(得分:1)

使用re

>>> import re
>>> matches = re.match('[01]*$', bin2dec)
>>> if matches:
...    process(bin2dec)

答案 7 :(得分:1)

如果您正在避免使用Python的内置方法(int(..., 2))作为学习练习,那么逻辑和Pythonic方法就是创建自己的错误类并构建错误检查到您的转换功能

class BinaryError(Exception):
    def __str__(self):
        return "Not a valid binary number"

def bin2dec(input_string):
    r = 0
    for character in input_string:
        if character == '0':
            r = r * 2
        elif character == '1':
            r = r * 2 + 1
        else:
            raise BinaryError()
    return r

while True:
    try:
        print bin2dec(raw_input("Please enter a binary number: "))
    except BinaryError:
        print "Enter a Binary number. Please try again.\n"
    else:
        break