[Tutor] Additional help

Ahmet Can KEPENEK ahmetcan196 at gmail.com
Mon Feb 11 21:21:25 CET 2013


Hello,
I used regular expression module of python. I checked binary and denary
numbers. If input is invalid i ask again. I edited your code. Code is below
follow as .


import re
def show_menu():
 print("=======================")
 print("1-binary to denary")
 print("2-denary to binary")
 print("3-exit")
 print("=======================")


while True:
    show_menu()

    choice = raw_input("please enter an option: ")

    if choice == '1':
        binary = raw_input("Please enter a binary number: ")
        if re.match("^[0-1]*$", binary):
            denary = 0
            place_value = 1

            for i in binary [::-1]:
                        denary += place_value * int(i)
                        place_value *= 2

            print("The result is",denary)

        else:
            print("Warning! Please enter a binary number")
            continue

    elif choice == '2':
        denary2 = raw_input("Please enter a denary number: ")
        if re.match("^[0-9]*$", denary2):
            denary2 = int(denary2)
            remainder = ''
            while denary2 > 0:
                remainder = str(denary2 % 2) + remainder
                denary2 >>= 1
            print("The result is",remainder)

        else:
            print("Warning! Please enter a denary number")
            continue

    elif choice == '3':
     break

    elif choice not in '1' or '2' or '3':
        print("Invalid input-try again!")






Output is
----------
=======================
1-binary to denary
2-denary to binary
3-exit
=======================
please enter an option: 1
Please enter a binary number: 110
('The result is', 6)
=======================
1-binary to denary
2-denary to binary
3-exit
=======================
please enter an option: 1
Please enter a binary number: 12
Warning! Please enter a binary number
=======================
1-binary to denary
2-denary to binary
3-exit
=======================
please enter an option: 3
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130211/23b4ec3d/attachment-0001.html>


More information about the Tutor mailing list