【问题标题】:How to check if a value is binary or not如何检查一个值是否是二进制的
【发布时间】:2018-05-09 02:00:12
【问题描述】:

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

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

提前谢谢你!

【问题讨论】:

  • 不要发布链接或图片。剪切并粘贴问题中的实际代码,以便人们可以执行相同的操作来运行您的代码和/或更改它以获得答案。请参阅How to Ask 以及如何创建minimal reproducible example
  • 二进制数必须由 0 和 1 组成。从这里开始,由您决定。如果你说这个数字是二进制的,它就是二进制的。例如 101101011 由 0 和 1 组成,但它可以是十进制、十六进制、二进制或其他。
  • @MarkTolonen,谢谢你,会改进的。

标签: python binary converter


【解决方案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中的所有数字是否为10。如果没有数字,则变量 binary 将更改为 False。当程序成功遍历整个值,并且binaryTrue 时,它会退出循环。

【讨论】:

    【解决方案2】:
    def isBinary(num):
        for i in str(num):
            if i in ("0","1") == False:
                return False
        return True
    

    【讨论】:

    • 如果num 没有转换成整数怎么办?
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2014-02-10
      • 2019-04-27
      • 1970-01-01
      • 2022-01-13
      • 1970-01-01
      • 2010-10-25
      • 1970-01-01
      • 2011-03-06
      • 1970-01-01
      相关资源
      最近更新 更多