Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a input is in binary format(1 and 0)?

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
like image 558
DaCruzR Avatar asked Sep 15 '13 11:09

DaCruzR


3 Answers

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
like image 191
alecxe Avatar answered Nov 14 '22 10:11

alecxe


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.

like image 45
Imre Kerr Avatar answered Nov 14 '22 10:11

Imre Kerr


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))
like image 5
tamasgal Avatar answered Nov 14 '22 10:11

tamasgal