[Tutor] Creating an Invalid Message for user

Alan Gauld alan.gauld at btinternet.com
Sat Apr 19 02:18:08 CEST 2014

On 18/04/14 22:19, Saba Usmani wrote:
> I am meant to design code for a program that converts from binary number
> to decimal and vice versa.

First, you know that python includes functions for doing that already 
right? So you are just doing this as a learning exercise?

> while loop:
>      bord = raw_input("Enter b for binary or d decimal or exit to exit")
>      if bord == "b":
>          d = 0
>          b = 0
>          factor = 1;
>          b = raw_input ("Enter Binary Number:")
>          b=b.lstrip("0")

Before converting to an int check each character is in the numeric range 
you need. For binary thats like

for ch in inputstring:
     if ch not in "01":
        # process invalid input

For decimal its

for ch in inputstring:
    if ch not in "0123456789":
     # process bad input.

You could put that in a function and pass in the
numbers as a parameter...

If you accept floats as input then it gets a whole
lot more complicated. but you are converting to int
so I assume its ints you expect.

Alan G
Author of the Learn to Program web site

More information about the Tutor mailing list