[Tutor] Creating an Invalid message for user

Mark Lawrence breamoreboy at yahoo.co.uk
Sat Apr 12 02:09:10 CEST 2014


On 11/04/2014 21:58, Saba Usmani wrote:
> Hi,
>
> I am meant to design code for a program that converts from binary number
> to decimal and vice versa.
>
> This is what i have so far:
>
> print "Welcome to the binary and decimal converter"
> loop = True
> 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")
>          b = int(b)
>          while(b > 0):
>              if((int(b) % 10) == 1):
>                  d += factor
>              b /= 10
>              factor = factor * 2
>          print "The Decimal Number is: ", d
>      elif bord == "d":
>          x=0
>          n=int(input('Enter Decimal Number: '))
>          x=n
>          k=[] # array
>          while (n>0):
>              a=int(float(n%2))
>              k.append(a)
>              n=(n-a)/2
>          k.append(0)
>          string=""
>          for j in k[::-1]:
>              string=string+str(j)
>          print('The binary Number for %d is %s'%(x, string))
>      elif bord == "exit" :
>          print "Goodbye"
>          loop = False
>
> - This code does not recognize invalid inputs e.g in the binary to
> decimal conversion, if I enter 10021 it will not inform me,the user,
> that the input is invalid. The same problem occurs with the decimal to
> binary conversion - if i enter 123&&gf I am not told to try again with a
> valid input  - how do I implement this in the code above
>
> Thanks
> Saba
>

https://docs.python.org/3/tutorial/errors.html#handling-exceptions is as 
good a starting point as any.

-- 
My fellow Pythonistas, ask not what our language can do for you, ask 
what you can do for our language.

Mark Lawrence

---
This email is free from viruses and malware because avast! Antivirus protection is active.
http://www.avast.com




More information about the Tutor mailing list