如何检查一个值是二进制还是n

2024-04-20 02:02:08 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

提前谢谢你!在


Tags: thetoinnumberinputifisdef
3条回答
def isBinary(num):
    for i in str(num):
        if i in ("0","1") == False:
            return False
    return True

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

输出示例:

^{pr2}$

要检查一个数字是否为二进制,有两个步骤:检查它是否为整数,以及检查它是否只包含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还是{}。如果数字不是,变量binary将变为False。当程序成功地迭代了整个值,并且binaryTrue,它将从循环中中断。在

相关问题 更多 >