[Tutor] Recognising Errors
Saba Usmani
sabausmani at outlook.com
Sun Apr 20 20:06:26 CEST 2014
Hi,
I have designed some code, but I want it to be able to recognize invalid inputs - 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?
print "Welcome to the binary -> decimal / decimal -> binary converter!"loop = Truewhile 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") binary_num = int(binary_num) while(binary_num > 0): if((int(binary_num) % 10) == 1): 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: ')) z=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 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.
Thanks
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20140420/b68dec31/attachment.html>
More information about the Tutor
mailing list