如何检查值是否为二进制

时间:2017-11-25 07:40:41

标签: python binary converter

我制作了一个将二进制转换为八进制,十进制和十六进制值的程序。如何检查用户的输入值是否为二进制数? 这是代码:

def repeat1():
    if choice == 'B' or choice == 'b':
        x = input("Go on and enter a binary number: ")
        y = int(x, 2)
        print(x, "in octal is", oct(y))
        print(x, "in decimal is", y)
        print(x, "in hexidecimal is", hex(y))
        print(" ")
        def tryagain1(): 
            print("Type '1' to convert from the same number base")
            print("Type '2' to convert from a different number base")
            print("Type '3' to stop")
            r = input("Would you like to try again?")
            if r == '1':
                repeat1()
            elif r == '2':
                loop()
            elif r == '3':
                print("Thank you for using the BraCaLdOmbayNo Calculator!")
            else:
                print("You didn't enter any of the choices! Try again!")
                tryagain1()
        tryagain1()

提前谢谢!

3 个答案:

答案 0 :(得分:1)

要检查数字是否为二进制,有两个步骤:检查它是否为整数,并检查它是否只包含1和0。

while True:
    try:
        x = int(input("Enter binary number"))
    except ValueError: # If value is not an integer
        print('Must be a binary number (contain only 1s and 0s)')
    else:
        # Iterates through all digits in x
        for i in str(x):
            if i in '10': # If digit is 1 or 0
                binary = True
            else:
                binary = False
                break
        if binary == False:
            print('Must be a binary number (contain only 1s and 0s)')
        else:
            break # Number is binary, you are safe to break from the loop
print(x, "Is Binary")

要求用户输入一个数字,程序会尝试将其转换为整数。如果程序返回ValueError,则表示输入不是整数,程序将打印该数字不是二进制,并且while循环将再次启动。如果数字成功转换为整数,程序将遍历数字(您必须转换为字符串,因为整数不可迭代)并检查x中的所有数字是1还是{ {1}}。如果数字不是,则变量0将更改为binary。当程序成功迭代整个值并且Falsebinary时,它会从循环中断开。

答案 1 :(得分:0)

fetch(slink, {method: "POST", headers:{
	"Content-type":"application/json"
}, body: {request: "Site Request"}}).then((resp)=>{
	return resp.json();

答案 2 :(得分:0)

我认为try-except是最好的方法。如果int(num, 2)有效,则num为二进制。这是我的代码:

while True:
    num = input("Number : ")
    try:
        decimal = int(num, 2) # Try to convert from binary to decimal
    except:
        print("Please type a binary number")
        continue              # Ask a new input

    binary = bin(decimal) # To prefix 0b
    octal = oct(decimal)
    hexadecimal = hex(decimal)

    print(decimal, binary, octal, hexadecimal)

示例输出:

Number : john
Please type a binary number
Number : ...
Please type a binary number
Number : 12546
Please type a binary number
Number : 10000101011
1067 0b10000101011 0o2053 0x42b
Number : 100111011
315 0b100111011 0o473 0x13b