I have made a program however I wanted to add an exception if the user inputs is not in a binary format. I have tried many times adding exceptions but I can't seem to get it to work. The below is the program code. I would appreciate if someone could help.
import time
error=True
n=0
while n!=1:
print"***Welcome to the Bin2Dec Converter.***\n"
while error:
try:
bin2dec =raw_input("Please enter a binary number: ")
error=False
except NameError:
print"Enter a Binary number. Please try again.\n"
time.sleep(0.5)
except SyntaxError:
print"Enter a Binary number. Please try again.\n"
time.sleep(0.5)
#converts bin2dec
decnum = 0
for i in bin2dec:
decnum = decnum * 2 + int(i)
time.sleep(0.25)
print decnum, "<<This is your answer.\n" #prints output
Better to ask for forgiveness. Try to convert it to integer using int(value, 2)
:
while True:
try:
decnum = int(raw_input("Please enter a binary number: "), 2)
except ValueError:
print "Enter a Binary number. Please try again.\n"
else:
break
print decnum
int(bin2dec, 2)
will throw a ValueError if the input isn't in binary format. But of course that solves the whole problem for you.
Using set()
:
def is_binary(x):
return set(input_string) <= set('01')
input_string = "0110110101"
print(is_binary(input_string))
input_string = "00220102"
print(is_binary(input_string))
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