如何检查一个值是否为二进制

How to check if a value is binary or not

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

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()

提前致谢!

def isBinary(num):
    for i in str(num):
        if i in ("0","1") == False:
            return False
    return True

要检查一个数是否为二进制,有两个步骤:检查它是否为整数,以及检查它是否只包含 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")

要求用户输入一个数字,程序会尝试将其转换为整数。如果程序returns a ValueError,这意味着输入不是一个整数,程序会打印出这个数不是二进制的,while循环会重新开始。如果数字成功转换为整数,程序将遍历数字(您必须转换为字符串,因为整数不可迭代)并检查 x 中的所有数字是否为 10。如果数字不是,变量 binary 将变为 False。当程序成功迭代整个值,并且 binaryTrue 时,它会从循环中跳出。

我认为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