0

My goal is to find any value other than 1 or 0 in list and throw an error and break out of the loop.

At the moment it can check for any non-integer values just fine but i wish to avoid certain numbers (2-9). I tried checking if x != '1' or x != '0' but that didn't work.

I appreciate any help.

decimalTotal = 0
digit = 0
index = 0
power = 7
flag = 'false'

#get an 8-bit binary number
binaryNumber = input("Please enter an 8-bit binary number: ")
binary_list = list(binaryNumber)

if len(binary_list) != 8:
    print()
    print("You did not enter an 8-bit length.")
    print()


for x in binary_list:
    while (power >= 0):    
        try:
            (int(binary_list[index]))
        except ValueError:
             flag = 'true'
             break
        else:
            decimalTotal += (int(binary_list[index])) * (2**(power))
            index += 1
            power -= 1



if flag == 'false':
    print()
    print("The decimal value is: ", decimalTotal)
    print()

else:
    print()
    print("Invalid binary value entered.")
    print()
Cornel
  • 180
  • 2
  • 4
  • 13
  • you have to check if x!='0' and x!= '1', with "and", not "or". – Christian Sloper Nov 10 '18 at 21:50
  • Just a minor note: Instead of 'true' use True and instead of 'false' use False. Like this you would use the real Python Boolean values, see https://stackoverflow.com/questions/1748641/how-do-i-use-a-boolean-in-python – quant Nov 10 '18 at 21:50
  • Would `if not re.match('[01]{8}$', binaryNumber)` do what you want here? – Jon Clements Nov 10 '18 at 21:52
  • In case you are interested, the most easiest way to write such a program would be print(int(input("Please enter an 8-bit binary number: "), 2)), see https://stackoverflow.com/questions/8928240/convert-base-2-binary-number-string-to-int – quant Nov 10 '18 at 21:53
  • @quant yup and catch an exception for non-zero/ones and maybe check the length but yeah... :) – Jon Clements Nov 10 '18 at 21:53
  • Probably though - the regex above to `print('not valid!')` and then `else: print('result is:', int(binaryNumber, 2))` – Jon Clements Nov 10 '18 at 21:55

1 Answers1

1

If you definitely need to ensure it's exactly 8, 0 or 1s, then probably an easy way is to do:

import re

binaryNumber = input("Please enter an 8-bit binary number: ")
if not re.match('[01]{8}$', binaryNumber):
    print('You did not enter exactly 8 zeros or ones.')
else:
    print('Your number as decimal is:', int(binaryNumber, 2))

Otherwise, if you don't care whether it's exactly 8 bits, but can be less or more and just want to show it as a decimal, then you can do:

try:
    print('Your number as decimal is:', int(binaryNumber, 2))
except ValueError: # couldn't be interpreted as binary
    print('Your number was not a valid binary string')
Jon Clements
  • 138,671
  • 33
  • 247
  • 280