如何改进此代码的功能

时间:2014-06-27 10:55:49

标签: python

a1 = input("Enter an 8 bit  binary number to convert: ")

a1 = list(a1)

ok = False;

if a1[0] == '0':
    ok = True

if a1[0] == '1':
    ok = True

if a1[1] == '0':
    ok = True

if a1[1] == '1':
    ok = True

if a1[2] == '0':
    ok = True

if a1[2] == '1':
    ok = True

if a1[3] == '0':
    ok = True

if a1[3] == '1':
    ok = True

if a1[4] == '0':
    ok = True

if a1[4] == '1':
    ok = True

if a1[5] == '0':
    ok = True

if a1[5] == '1':
    ok = True

if a1[6] == '0':
    ok = True

if a1[6] == '1':
    ok = True

if a1[7] == '0':
    ok = True

if a1[7] == '1':
    ok = True

if ok == True:
    print("Number is binary!")


n1 = 0

if a1[7] == '1':
    n1 = 1

if a1[6] == '1':
    n1 = n1 + 2

if a1[5] == '1':
    n1 = n1 + 4

if a1[4] == '1':
    n1 = n1 + 8

if a1[3] == '1':
    n1 = n1 + 16

if a1[2] == '1':
    n1 = n1 + 32

if a1[1] == '1':
    n1 = n1 + 64

if a1[0] == '1':
    n1 = n1 + 128

print("Denary number is: " + str(n1))

2 个答案:

答案 0 :(得分:3)

使用set

a1 = input("Enter an 8 bit  binary number to convert: ")

if set(a1) <= set('01'):
    print("Number is binary!")

仅当set(a1)set('01')的一个子集时才会出现这种情况:

>>> set('10011') <= set('01')
True
>>> set('10011abc') <= set('01')
False

您也可以使用例外(和int()进行二进制 - >整数转换):

try:
    n1 = int(a1, 2)
except ValueError:
    print("Not binary")
else:
    print("Number is binary")
    print("Denary number is: {}".format(n1))

这样做的另一个好处是可以一步将二进制输入转换为整数。

如果您不想或可以使用int(),请使用循环转换回来并为每个二进制数字使用<< left-shift,并| binary bitwise OR添加新数字:< / p>

n1 = 0
for digit in a1:
    n1 = (n1 << 1) | (1 if digit == '1' else 0)

这是获取数字的一种全面的方式,但至少你现在正在使用二进制逻辑。

答案 1 :(得分:1)

您可以使用python中的all()方法:

a1 = raw_input("Enter an 8 bit  binary number to convert: ")

print all(i in ('0','1') for i in a1)