Advertisement
billymcguffin

Fun with baskets

Aug 28th, 2014
38
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 13.28 KB | None | 0 0
  1. # Basket Program!
  2. # Cole Schultz
  3.  
  4.  
  5. class Basket:
  6.     """ This class represents a virtual 'basket' of objects which have a user defined type in common.
  7.    It includes functions for manipulating the list and type of the basket while keeping the actual variables
  8.    encapsulated.
  9.    """
  10.  
  11.     def __init__(self, basket_type):
  12.         # Here we set up the basket with the input basket type and a blank list
  13.         self._basket_type = basket_type
  14.         self._basket_list = []
  15.  
  16.     def __repr__(self):
  17.         # This function is called whenever the program wants to print this class. In this case, we just print out
  18.         # the type of the Basket.
  19.         return self.get_type()
  20.  
  21.     def get_type(self):
  22.         return self._basket_type
  23.  
  24.     def set_type(self, new_type):
  25.         self._basket_type = new_type
  26.  
  27.     def get_items(self):
  28.         return self._basket_list
  29.  
  30.     def add_item(self, item, position=None):
  31.         # This function will place the item in the index before "position". If no position is specified, it puts it
  32.         # at the end of the list.
  33.  
  34.         if position is not None:
  35.             self._basket_list.insert(position, item)
  36.         else:
  37.             self._basket_list.append(item)
  38.  
  39.     def remove_item(self, item):
  40.         self._basket_list.remove(item)
  41.  
  42.     def replace_item(self, item_to_replace, new_item):
  43.         # Finds the location of the item to replace, removes it, then places the new item in that position.
  44.        
  45.         index = self._basket_list.index(item_to_replace)
  46.         self.remove_item(item_to_replace)
  47.         self.add_item(new_item, index)
  48.  
  49.  
  50. def create_user_basket(basket_list):
  51.     """ This function creates a new basket that the user can choose the type of. It is called automatically at the start
  52.    of the "game". It is also called when the user chooses to make a new basket from the main menu.
  53.    """
  54.  
  55.     valid_basket = False
  56.  
  57.     while not valid_basket:
  58.         basket_type = input("What kind of things do you want to put in your basket? ")
  59.  
  60.         for basket in basket_list:
  61.             # If the input basket type matches any existing baskets, give an error message, then leave the for loop.
  62.             if basket.get_type() == basket_type:
  63.                 print("A basket of that type already exists!")
  64.                 break
  65.         else:
  66.             # If we successfully get through the whole basket list without a match, we have a valid basket.
  67.             valid_basket = True
  68.  
  69.     print("OK, we'll make a basket of " + basket_type + ".\n")
  70.     the_basket = Basket(basket_type)  # Create a new basket
  71.     basket_list.append(the_basket)  # Add it to the list
  72.     return the_basket  # Return it if we ever need it (probably wont, but just in case).
  73.  
  74.  
  75. def do_switch_basket(basket_list, current_basket_index):
  76.     """ This function is called when the user chooses to switch baskets from the main menu."""
  77.  
  78.     # If they only have one basket, send them back to the main menu with the current index.
  79.     if len(basket_list) == 1:
  80.         print("You only have one basket!")
  81.         return current_basket_index
  82.  
  83.     print("Which basket would you like to edit?")
  84.     while True:
  85.         # enumerate() returns a tuple in the form (index, item). We use this to place the numbers before each menu
  86.         # item. We start the counting at 1 so that the numbering starts at.
  87.         for index, item in enumerate(basket_list, 1):
  88.             print("\t", str(index) + ")", item)  # For each menu item, print a tab, number, then type of basket.
  89.  
  90.         menu_input = input("")  # We already printed the prompt, so just have a blank prompt for the input function.
  91.  
  92.         try:
  93.             # try converting the user's input into an int.
  94.             menu_selection = eval(menu_input)
  95.         except(NameError, TypeError):
  96.             # if it cannot be made into an int, give an error message
  97.             print("You did not enter a valid menu selection. Please select a valid menu selection.\n")
  98.         else:
  99.             if 0 < menu_selection <= len(basket_list):
  100.                 # make sure the selection matches a menu item.
  101.                 return menu_selection - 1
  102.             else:
  103.                 print("The number you entered does not correspond to a menu item.\n")
  104.  
  105.  
  106. def do_basket_info(current_basket):
  107.     """ This function is called when the user chooses tell me about this basket from the main menu. It prints the
  108.    type of items in the basket along with any items that are currently in it.
  109.    """
  110.  
  111.     print("This basket holds " + current_basket.get_type() + "!\n")
  112.  
  113.     if len(current_basket.get_items()) == 0:
  114.         # If there are no items in the basket (length of list is 0), give a special message.
  115.         print("There are no items in this basket!")
  116.         return False
  117.     else:
  118.         # If there are items, print them!
  119.         print("The following items are in this basket:")
  120.  
  121.         # enumerate() returns a tuple in the form (index, item). We can use it to see where we are in the list.
  122.         # we start the counting at 1 so that the index of the last item will equal the length of the list.
  123.         for index, item in enumerate(current_basket.get_items(), 1):
  124.             # Print the item string. The "end=''" makes sure the print statement does not add a newline
  125.             print(item, end='')
  126.             if index != len(current_basket.get_items()):
  127.                 # If the item is not the last item in the list, put a comma after it.
  128.                 print(", ", end='')
  129.  
  130.         print("\n")
  131.         return True
  132.  
  133.  
  134. def do_add_item(current_basket):
  135.     """ This function is called when the user chooses to add items from the main menu. It allows the user to input
  136.    multiple items at once, delimited by commas. It only checks if an item is already in the list.
  137.    """
  138.  
  139.     new_item_input = input("What items do you want to add to the basket? (separate items with commas) ")
  140.  
  141.     new_item_list = new_item_input.split(",")  # this returns a list of all of the items separated by commas.
  142.  
  143.     # Loop through the list of items, and do some validation.
  144.     for new_item in new_item_list:
  145.         # This removes spaces from the outside of each item. It does not remove spaces inside items.
  146.         # EG, if the user input the string literal "  spam and eggs ", it would return "spam and eggs".
  147.         new_item = new_item.strip()
  148.  
  149.         if new_item == "":
  150.             # Here we ignore any items which aren't anything.
  151.             pass
  152.         elif new_item in current_basket.get_items():
  153.             # Here we ignore any items which are arleady in the basket.
  154.             print(new_item, "is already in the basket!")
  155.         else:
  156.             # Here we add valid items to the basket.
  157.             print(new_item, "added to the basket!")
  158.             current_basket.add_item(new_item)
  159.  
  160.     print()  # Add an extra newline for formatting purposes.
  161.  
  162.  
  163. def do_remove_item(current_basket):
  164.     """ This function is called when the user chooses to remove an item from the main menu. It validates the user's
  165.    input, then sends the input to the basket object to remove.
  166.    """
  167.  
  168.     while True:
  169.         item_to_remove = input("What item do you want to remove? ")
  170.         item_to_remove = item_to_remove.strip()  # remove spaces from the ends so that comparison is easier
  171.  
  172.         try:
  173.             # Here we're validating the input by trying to remove the item.
  174.             current_basket.remove_item(item_to_remove)
  175.         except ValueError:
  176.             # If the item isn't in the list (we can't remove it), then we go here and give a message. Then we go back
  177.             # and ask again.
  178.             print(item_to_remove, "is not in the basket!")
  179.         else:
  180.             # If the removal goes through properly, we tell the user and then skedaddle.
  181.             print(item_to_remove, "removed from the basket!\n")
  182.             return
  183.  
  184.  
  185. def do_replace_item(current_basket):
  186.     """ This function is called when the user chooses to replace an item from the main menu. It validates the user's
  187.    choices, then tells the basket object to do the replacement.
  188.    """
  189.  
  190.     # a couple loop variables
  191.     valid_replacee = False  # if the user gives a valid item to replace, it wont ask for that again.
  192.     valid_replacement = False  # if the user gives a valid new item, it wont ask for that again.
  193.  
  194.     while True:
  195.         if not valid_replacee:  # we only ask them for an item to replace if we don't already have a valid one.
  196.             item_to_replace = input("What item do you want to replace? ")
  197.             item_to_replace = item_to_replace.strip()  # remove any spaces so that comparisons are easier
  198.  
  199.             if item_to_replace not in current_basket.get_items():
  200.                 print(item_to_replace, " is not in the basket!")
  201.                 continue  # go back to the top of the while loop
  202.  
  203.             valid_replacee = True
  204.  
  205.         if not valid_replacement:  # we only ask them for an item to replace if we don't already have a valid one.
  206.             new_item = input("What item to you want to exchange for " + item_to_replace + "? ")
  207.             new_item = new_item.strip()
  208.  
  209.             if new_item in current_basket.get_items():
  210.                 print(new_item, "is already in the basket!")
  211.                 continue  # return to the top of the while loop
  212.  
  213.             valid_replacement = True
  214.  
  215.         current_basket.replace_item(item_to_replace, new_item)  # we let the basket class handle the replacement
  216.         print("Replaced", item_to_replace, "with", new_item + "!\n")
  217.         return
  218.  
  219.     # **NOTE: For this function we don't use the try...except method of validation because we want to validate the
  220.     # **item to replace and the new item separately. If we just tried to send it to the basket object, it would only
  221.     # **send one exception, plus it wouldn't complain about adding the same item to the basket twice.
  222.  
  223.  
  224. def do_main_menu(current_basket):
  225.     """ This function presents a main menu to the user and validates their selection before sending it back to the
  226.    caller.
  227.    """
  228.  
  229.     print("What would you like to do with your", current_basket.get_type(), "basket?\n")
  230.  
  231.     # a list of the menu items available to the user.
  232.     menu_items = [
  233.         "Add items!",
  234.         "Remove an item!",
  235.         "Replace an item!",
  236.         "Can you tell me about this basket?",
  237.         "Can I switch to a different basket?",
  238.         "Create a new basket!",
  239.         "Quit!"
  240.     ]
  241.  
  242.     # this loop will repeat until a valid input is given
  243.     while True:
  244.  
  245.         # This prints out each option in the menu items list with a number in front of it.
  246.         for index, item in enumerate(menu_items, 1):
  247.             print("\t", str(index) + ")", item)
  248.  
  249.         # we already printed the prompt with the for loop above, so we just display a blank prompt for the input.
  250.         menu_input = input("")
  251.  
  252.         # here we validate the user's selection
  253.         try:
  254.             menu_selection = eval(menu_input)  # try to convert the input (which is a string) into an int
  255.         except(NameError, TypeError):
  256.             # if the input cannot be made into an int, the program jumps here. We display an error message, then
  257.             # the program will just go back to the top of the while loop.
  258.             print("You did not enter a valid menu selection. Please select a valid menu selection.\n")
  259.         else:
  260.             # this code is executed only if the input can be converted to an int.
  261.             # first we make sure that the number they entered matches a menu selection.
  262.             if 0 < menu_selection <= len(menu_items):
  263.                 # if the number is valid we return, which automatically breaks out of the while loop.
  264.                 return menu_selection
  265.             else:
  266.                 print("The number you entered does not correspond to a menu item.\n")
  267.  
  268.  
  269. def main():
  270.     """ This is the main function which is the base application which calls all the other functions and creates
  271.    classes as needed.
  272.    """
  273.  
  274.     print("Let's Make a Basket!\n")
  275.  
  276.     # First we make a list of baskets and set the "current basket" to the first item in the list (which currently
  277.     # doesn't exist), but it will by the time we use it
  278.     my_baskets = []
  279.     current_basket_index = 0
  280.     create_user_basket(my_baskets)
  281.  
  282.     running = True
  283.  
  284.     while running:
  285.         menu_selection = do_main_menu(my_baskets[current_basket_index])
  286.  
  287.         # run the correct function based on the menu option selected previously
  288.         if menu_selection == 7:
  289.             running = False
  290.         elif menu_selection == 6:
  291.             create_user_basket(my_baskets)
  292.         elif menu_selection == 5:
  293.             current_basket_index = do_switch_basket(my_baskets, current_basket_index)
  294.         elif menu_selection == 4:
  295.             do_basket_info(my_baskets[current_basket_index])
  296.         elif menu_selection == 3:
  297.             do_replace_item(my_baskets[current_basket_index])
  298.         elif menu_selection == 2:
  299.             do_remove_item(my_baskets[current_basket_index])
  300.         elif menu_selection == 1:
  301.             do_add_item(my_baskets[current_basket_index])
  302.         else:
  303.             print("I have no idea how you got here, but why don't you start over?")
  304.  
  305.     return True
  306.  
  307.  
  308. # This is where the program begins. Everything occurs in the main() function, but we need to call it here
  309. # to get things started.
  310. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement