5

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

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
4

8 回答 8

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
于 2013-09-15T11:55:11.783 回答
6

int(bin2dec, 2)如果输入不是二进制格式,将抛出 ValueError 。但是,这当然可以为您解决整个问题。

于 2013-09-15T11:54:42.750 回答
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))
于 2013-09-15T11:56:11.120 回答
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
于 2013-09-15T11:53:48.717 回答
2

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

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

于 2013-09-15T11:56:19.307 回答
1
>>> b = '01011'
>>> not(b.translate(None, '01'))
True
>>> b = '21011'
>>> not(b.translate(None, '01'))
False
于 2013-09-15T11:58:15.770 回答
1

使用re

>>> import re
>>> matches = re.match('[01]*$', bin2dec)
>>> if matches:
...    process(bin2dec)
于 2013-09-15T11:58:43.070 回答
1

int(..., 2)如果您避免使用Python的内置方式(

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
于 2013-09-15T12:41:33.397 回答