0

This is my sample code for converting a binary number to a decimal number with steps

def binaryToDecimal(b2d):
    i = len(b2d) - 1
    total = 0
    for x in b2d:
        print("%d x 2^%d = %d" % (x, j, (x * 2 ** j)))
        total += (x * 2 ** j)
        j -= 1
    print("The decimal conversion would be", total)


binaryToDecimal([int(n) for n in input('Enter value: ')]) # this converts user input into a list

I would like it to show an error message if the user had inputted numbers other than 1's and 0's.

This is my take on it:

def binaryToDecimal(b2d):
    if 1 and 0 in b2d:
        *<proceed with program>*
    else:
        print("ERROR")

As for the problem with the top example, it works fine in some cases but in order for the program to proceed, both numbers 1's and 0's has to be inputted. Therefore, inputting '11' gives an error. And for some numbers like '0222' it would still proceed with the program even when there's a 2 in the list.

OJDylan
  • 27
  • 7

1 Answers1

0

Does it have to be custom code? Otherwise you could just use int(). For example:

valid = int('010101', base=2)
invalid = int('012345', base=2)

Props to this answer.

If you do want to customize, you could do e.g.:

def binaryToDecimal(b2d):
    try:
        output = int(b2d, base=2)
        print output
    except ValueError as e:
        custom_error_message = ('your custom error message\n'
                                '(original message: {})'.format(e.message))
        raise ValueError(custom_error_message)
    return output
djvg
  • 11,722
  • 5
  • 72
  • 103
  • @OJDylan: You wrote your own custom function `binaryToDecimal()` for the conversion. The built-in `int()` can also do the conversion, and it gives an error in case the user input is wrong. I thought that might be what you were looking for. – djvg Mar 09 '18 at 07:17
  • @OJDylan: I guess it depends on what is your actual question. Do you want to know the answer to the question in your title, or do you want to know how to do the conversion from binary to decimal? In case it is the former, my answer does not help you, but in case it is the latter, you might want to change the title of your question. – djvg Mar 09 '18 at 07:25
  • This program is made for users trying to understand conversion between base numbers. So as long as I show the conversion steps and also correcting user-made errors, it should be fine. – OJDylan Mar 09 '18 at 07:29
  • The initial code shown above is what I intend the program run like, it's just implementation of the error-checking mechanism that gives me problems with the code. I would try to analyze your codes much further. Thanks for the help – OJDylan Mar 09 '18 at 07:33