rks rks - 6 months ago 14
Python Question

How can I validate input to accept only binary numbers?

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

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.

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)

Answer

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. Handle any errors if it isn't.

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:

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