5

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
DaCruzR
  • 347
  • 2
  • 5
  • 14

8 Answers8

9

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
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • Yup - much more filled out than my answer :) – Jon Clements Sep 15 '13 at 11:55
  • 1
    I think it would be prettier to get rid of the useless `continue` and maybe move `break` into an `else` block. – ThiefMaster Sep 15 '13 at 11:57
  • This clearly demonstrates how to convert a binary number to decimal in Python (+1), but it's not what the OP asked... – Alex Chamberlain Sep 15 '13 at 12:03
  • 2
    @AlexChamberlain, it's an implicit check (converting only works for binary input), so this is kind of what the OP asked + a better way to handle the problem IMO – tamasgal Sep 15 '13 at 12:04
  • 1
    Note that this function allows more valid inputs than the OP's version. You should check whether the user input contains a `b` before calling `int(..., 2)`, otherwise inputs starting with the `0b` prefix will be allowed(which I believe is not something the OP wants, and anyway he should be aware of this change). – Bakuriu Sep 15 '13 at 12:15
  • Thanks for all your suggestions, if i could request someone to put the above in the context of my code. I'm still a beginer at python coding. Thanks – DaCruzR Sep 15 '13 at 14:12
6

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.

Imre Kerr
  • 2,388
  • 14
  • 34
5

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))
tamasgal
  • 24,826
  • 18
  • 96
  • 135
2

Using all:

>>> b = '01011'
>>> all(c in '01' for c in b) # OR  c in ('0', '1')
True
>>> b = '21011'
>>> all(c in '01' for c in b) # OR  c in ('0', '1')
False
falsetru
  • 357,413
  • 63
  • 732
  • 636
2

The proper way to do this (i.e. if it's not a stupid homework exercise) is using int(your_string, 2) and catching ValueError which is raised if the string contains an invalid character.

http://docs.python.org/2/library/functions.html#int

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
1
>>> b = '01011'
>>> not(b.translate(None, '01'))
True
>>> b = '21011'
>>> not(b.translate(None, '01'))
False
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
1

Using re:

>>> import re
>>> matches = re.match('[01]*$', bin2dec)
>>> if matches:
...    process(bin2dec)
Alex Chamberlain
  • 4,147
  • 2
  • 22
  • 49
  • @JonClements Thanks, I agree with the `$`; I always forget `match` has an implicit `^`, but not a `$`. `*` vs `+` is a question for the OP really. – Alex Chamberlain Sep 15 '13 at 12:06
1

If you are avoiding Python's built in way of doing this (int(..., 2)), as a learning exercise, then a logical and Pythonic approach would be to make your own error class and build the error checking in to your conversion function.

class BinaryError(Exception):
    def __str__(self):
        return "Not a valid binary number"

def bin2dec(input_string):
    r = 0
    for character in input_string:
        if character == '0':
            r = r * 2
        elif character == '1':
            r = r * 2 + 1
        else:
            raise BinaryError()
    return r

while True:
    try:
        print bin2dec(raw_input("Please enter a binary number: "))
    except BinaryError:
        print "Enter a Binary number. Please try again.\n"
    else:
        break
Stuart
  • 9,597
  • 1
  • 21
  • 30