I'm doing a binary to decimal converter in python 3.4.4 and it's pretty much finished except for the fact that I would like to check that the binary number entered by the user is indeed a binary number (check if the string is only made of o and 1) but I'm unsure what to do.
here's the program:
binary=input("Enter a binary number")
bit=len(binary)
result=0
power=0
while bit>0:
result=result+int(binary[bit-1])*2**power
bit=bit-1
power=power+1
print(binary, " in decimal is equal to ", result, sep="")
hopefully someone can help me <3
Follow the EAFP approach, try to convert it to decimal via int()
and handle the ValueError
:
try:
int(binary, 2)
is_binary = True
except ValueError:
is_binary = False
If you must avoid using int(binary, 2)
and handle the exception, you could use the all()
function with a generator expression:
all(c in '01' for c in binary)
all()
with a generator expression will bail out early and return False
when a non-binary digit is found.
If you are already looping over all characters anyway you could just raise an exception in your loop:
binary=input("Enter a binary number")
bit=len(binary)
result=0
power=0
try:
while bit>0:
if binary[bit-1] not in '01':
raise ValueError('Not a binary string: %s' % binary)
result=result+int(binary[bit-1])*2**power
bit=bit-1
power=power+1
except ValueError:
print('%s is not a binary string')
else:
print(binary, " in decimal is equal to ", result, sep="")
Rather than use an index, your code could just loop over the reverse of the string, using numbers generated by enumerate()
as the power:
binary = input("Enter a binary number")
result = 0
try:
for power, bit in enumerate(reversed(binary)):
if bit not in '01':
raise ValueError('Not a binary string: %s' % binary)
result += int(bit) * 2 ** power
except ValueError:
print('%s is not a binary string')
else:
print(binary, " in decimal is equal to ", result, sep="")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With