如何验证输入以仅接受二进制数?

时间:2022-11-25 11:26:04

How can I validate some binary input to make sure that there are only 1s and 0s, not letters or other integers?

如何验证一些二进制输入以确保只有1和0,而不是字母或其他整数?

user_bin = (input('\nPlease enter binary number: '))

user_bin_list = list(user_bin)

while int(user_bin) < 0 or int(user_bin) > 1:
    print('Please make sure your number contains digits 0-1 only.')
    user_bin = (input('\nPlease enter binary number: '))

So far I can only get my function to not accept integers other then 1 or 0 but it wont let me enter 1 and 0 combined.

到目前为止,我只能让我的函数不接受除1或0之外的整数,但它不会让我输入1和0的组合。

The entire code:

整个代码:

#Prompt for and read user binary input
user_bin = list(input('\nPlease enter binary number: '))

user_bin_list = list(user_bin)
user_bin_len = len(user_bin_list)
powers_count = len(user_bin) - 1

index = 0
decimal_num = 0

while powers_count >= 0:
    decimal_num += (int(user_bin[index]))*(2**(powers_count))
    index += 1
    powers_count -= 1
print('\nDecimal number: ',decimal_num)

2 个解决方案

#1


In general, the easiest way to validate a user's input is to:

通常,验证用户输入的最简单方法是:

  1. Treat it as if it is what you expect; and
  2. 把它视为你所期望的;和

  3. Handle any errors if it isn't.
  4. 如果不是,请处理任何错误。

This is in line with Python's "easier to ask forgiveness than permission" style. In this case, you're expecting an input you can interpret as binary:

这符合Python的“更容易请求宽恕而非许可”的风格。在这种情况下,您期望输入可以解释为二进制:

while True:
    try:
        user_bin = int(input('\nPlease enter binary number: '), 2)
    except ValueError:
        print('Please make sure your number contains digits 0-1 only.')
    else:
        break

#2


Use the second parameter (base) of the int constructor:

使用int构造函数的第二个参数(base):

while True:
    user_bin_inp = raw_input('\nPlease enter a binary number: ')
    try:
        user_bin = int(user_bin_inp, 2)
    except ValueError:
        print("{!r} is not a valid binary integer.".format(user_bin_inp))
        continue
    break

#1


In general, the easiest way to validate a user's input is to:

通常,验证用户输入的最简单方法是:

  1. Treat it as if it is what you expect; and
  2. 把它视为你所期望的;和

  3. Handle any errors if it isn't.
  4. 如果不是,请处理任何错误。

This is in line with Python's "easier to ask forgiveness than permission" style. In this case, you're expecting an input you can interpret as binary:

这符合Python的“更容易请求宽恕而非许可”的风格。在这种情况下,您期望输入可以解释为二进制:

while True:
    try:
        user_bin = int(input('\nPlease enter binary number: '), 2)
    except ValueError:
        print('Please make sure your number contains digits 0-1 only.')
    else:
        break

#2


Use the second parameter (base) of the int constructor:

使用int构造函数的第二个参数(base):

while True:
    user_bin_inp = raw_input('\nPlease enter a binary number: ')
    try:
        user_bin = int(user_bin_inp, 2)
    except ValueError:
        print("{!r} is not a valid binary integer.".format(user_bin_inp))
        continue
    break