Use a set:
a1 = input("Enter an 8 bit binary number to convert: ")
if set(a1) <= set('01'):
print("Number is binary!")
This will only be true if set(a1)
is a subset of set('01')
:
>>> set('10011') <= set('01')
True
>>> set('10011abc') <= set('01')
False
You can also just use exceptions (and int() to do the binary -> integer conversion):
try:
n1 = int(a1, 2)
except ValueError:
print("Not binary")
else:
print("Number is binary")
print("Denary number is: {}".format(n1))
This has the added advantage of converting your binary input to an integer in one step.
If you don't want or can use int()
, convert back with a loop and use << left-shift for each binary digit, and | binary bitwise OR to add the new digit:
n1 = 0
for digit in a1:
n1 = (n1 << 1) | (1 if digit == '1' else 0)
This is rather a round-about way to get the number, but at least you are using binary logic now.