[Tutor] When I run this code, it just keeps repeating.

Bob Gailer bgailer at sbcglobal.net
Sun Jul 31 16:58:51 CEST 2005


At 06:55 PM 7/30/2005, Nathan Pinno wrote:
>...
>     elif cal_opt == 4:
>         X = input("First number:" )
>         Y = input("Second number:" )
>         if Y == 0:
>             print "Division by zero ot allowed!"
>             Y = input("Second number:" )
>         else:
>             print X, "/", Y, "= ",X / Y

Note that you give user a 2nd try but that input never reaches the print 
statement.

The following might be a bit of a stretch, but consider creating a list of 
lists to store the various menu options.
Doing this separates the high-level menu from lower-level code which is now 
not repetitive. To add/modify menu items one just extends/edits the list. 
Here's a "simple" example which ignores some things but gives you the idea. 
Warning untested code:

menuItems = [
  ["Add", "First number:", "Second number:",  "+", lambda(x,y:x+y)],
  ["Subtract", "First number:", "Second number:",  "-", lambda(x,y:x-y)],
  ["Exit"]]
# first item is the main menu prompt,
# 2nd and 3rd are the input prompts,
# 4th is the string representation of the operator,
# 5th is an anonymous function to do the calculation.

def menu():
   print "CALCULATE MENU"
   for option, menuItem in enumerate(menuItems):
     print str(option + 1) + ")", menuItem[0]

def cal():
   cal_opt = int(raw_input("Option: "))
   if 1 <= cal_opt <= len(menuItems):
     menuItem = menuItems[cal_opt - 1]
     if menuItem[0] = "Exit":return False
     prompt1, prompt2, oper, func =  menuItem[1:]
     X = input(prompt1)
     Y = input(prompt2)
     print X, oper, Y, "= ", func(X, Y)
   else:
     print "That's not an option. Try again."
   return True

print "Mini Calculator"
print "By Nathan Pinno"
print
while True:
   menu()
   if not cal(): break

Bob Gailer
phone 510 978 4454  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20050731/bc833b4a/attachment.htm


More information about the Tutor mailing list