[Tutor] Recognising Errors

Alan Gauld alan.gauld at btinternet.com
Mon Apr 21 01:15:14 CEST 2014


On 20/04/14 19:06, Saba Usmani wrote:

> ...such as a binary number with more than 8 digits or non-binary
> values. What do I have to add and where do I add it?

You need to either write a function to check the inputs - have you 
learned about functions yet? - or write some if/else checks after you 
read the input but before you convert it to a number.

Alternatively you can try to convert it and if it can't be converted 
catch the error - have you covered try/except yet?

> print "Welcome to the binary -> decimal / decimal -> binary converter!"
> loop = True
> while loop:
>      choice = raw_input("Enter b to convert from binary to decimal, d to
> convert from decimal to binary or e to exit")
>      if choice == "b":
>          decimal_num = 0
>          binary_num = 0
>          factor = 1;
>          binary_num = raw_input ("Enter Binary Number:")
>          binary_num=binary_num.lstrip("0")

Here is where you can test for the length of the string and whether any 
of the characters are non binary.

>          binary_num = int(binary_num)

Or you can wrap the above line in a try/except:

try: binary_num = int(binary_num)
except ValueError, TypeError:
      # deal with error here

>          while(binary_num > 0):
>              if((int(binary_num) % 10) == 1):

you don't need int() here, you already converted it above.

But it's an unusual way to convert a binary string to a decimal number.
Even if you don't use the built in conversion tools. Its more usual to 
just iterate over the characters adding powers of two.

>                  decimal_num += factor
>              binary_num /= 10
>              factor = factor * 2

>          print "The Decimal Equivalent is: ", decimal_num
>      elif choice == "d":
>          z=0
>          n=int(input('Enter Decimal Number: '))

You should not user input() in this way its extremely insecure
and even if its only you using the program you could still
accidentally type in something that causes harm. Use raw_input()
and int() as you did above, it is much safer.

>          z=n
>          k=[] # array
>          while (n>0):
>              a=int(float(n%2))

modulo two on an integer will always return 0 or 1.
There's no need to make it a float then convert back
to an int, its already an int.

>              k.append(a)
>              n=(n-a)/2
>          k.append(0)
>          string=""
>          for j in k[::-1]:
>              string=string+str(j)

The join() method of strings will do this all in one step
and be much faster.

>          print('The Binary Equivalent is %d is %s'%(z, string))
>      elif choice == "e" :
>          print "Thanks For Using This Converter!"
>          loop = False


> If for some reason you can't read this code properly as outlook has
> formatted it to look messy/cluttered; you do not have to respond.

True, but if you send unreadable  code you reduce the number
of people who can help you. Many of them experts in their field.
That's a lot of help to ignore!

Its not just Outlook that is the culprit - its how you have set
your Outlook options. Of course it would be good if Microsoft
made the defaults internet friendly but Microsoft have always
struggled with the idea that people don't all use their
products :-)

Fortunately my mail reader could cope!

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list