Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Basket Program!
- # Cole Schultz
- class Basket:
- """ This class represents a virtual 'basket' of objects which have a user defined type in common.
- It includes functions for manipulating the list and type of the basket while keeping the actual variables
- encapsulated.
- """
- def __init__(self, basket_type):
- # Here we set up the basket with the input basket type and a blank list
- self._basket_type = basket_type
- self._basket_list = []
- def __repr__(self):
- # This function is called whenever the program wants to print this class. In this case, we just print out
- # the type of the Basket.
- return self.get_type()
- def get_type(self):
- return self._basket_type
- def set_type(self, new_type):
- self._basket_type = new_type
- def get_items(self):
- return self._basket_list
- def add_item(self, item, position=None):
- # This function will place the item in the index before "position". If no position is specified, it puts it
- # at the end of the list.
- if position is not None:
- self._basket_list.insert(position, item)
- else:
- self._basket_list.append(item)
- def remove_item(self, item):
- self._basket_list.remove(item)
- def replace_item(self, item_to_replace, new_item):
- # Finds the location of the item to replace, removes it, then places the new item in that position.
- index = self._basket_list.index(item_to_replace)
- self.remove_item(item_to_replace)
- self.add_item(new_item, index)
- def create_user_basket(basket_list):
- """ This function creates a new basket that the user can choose the type of. It is called automatically at the start
- of the "game". It is also called when the user chooses to make a new basket from the main menu.
- """
- valid_basket = False
- while not valid_basket:
- basket_type = input("What kind of things do you want to put in your basket? ")
- for basket in basket_list:
- # If the input basket type matches any existing baskets, give an error message, then leave the for loop.
- if basket.get_type() == basket_type:
- print("A basket of that type already exists!")
- break
- else:
- # If we successfully get through the whole basket list without a match, we have a valid basket.
- valid_basket = True
- print("OK, we'll make a basket of " + basket_type + ".\n")
- the_basket = Basket(basket_type) # Create a new basket
- basket_list.append(the_basket) # Add it to the list
- return the_basket # Return it if we ever need it (probably wont, but just in case).
- def do_switch_basket(basket_list, current_basket_index):
- """ This function is called when the user chooses to switch baskets from the main menu."""
- # If they only have one basket, send them back to the main menu with the current index.
- if len(basket_list) == 1:
- print("You only have one basket!")
- return current_basket_index
- print("Which basket would you like to edit?")
- while True:
- # enumerate() returns a tuple in the form (index, item). We use this to place the numbers before each menu
- # item. We start the counting at 1 so that the numbering starts at.
- for index, item in enumerate(basket_list, 1):
- print("\t", str(index) + ")", item) # For each menu item, print a tab, number, then type of basket.
- menu_input = input("") # We already printed the prompt, so just have a blank prompt for the input function.
- try:
- # try converting the user's input into an int.
- menu_selection = eval(menu_input)
- except(NameError, TypeError):
- # if it cannot be made into an int, give an error message
- print("You did not enter a valid menu selection. Please select a valid menu selection.\n")
- else:
- if 0 < menu_selection <= len(basket_list):
- # make sure the selection matches a menu item.
- return menu_selection - 1
- else:
- print("The number you entered does not correspond to a menu item.\n")
- def do_basket_info(current_basket):
- """ This function is called when the user chooses tell me about this basket from the main menu. It prints the
- type of items in the basket along with any items that are currently in it.
- """
- print("This basket holds " + current_basket.get_type() + "!\n")
- if len(current_basket.get_items()) == 0:
- # If there are no items in the basket (length of list is 0), give a special message.
- print("There are no items in this basket!")
- return False
- else:
- # If there are items, print them!
- print("The following items are in this basket:")
- # enumerate() returns a tuple in the form (index, item). We can use it to see where we are in the list.
- # we start the counting at 1 so that the index of the last item will equal the length of the list.
- for index, item in enumerate(current_basket.get_items(), 1):
- # Print the item string. The "end=''" makes sure the print statement does not add a newline
- print(item, end='')
- if index != len(current_basket.get_items()):
- # If the item is not the last item in the list, put a comma after it.
- print(", ", end='')
- print("\n")
- return True
- def do_add_item(current_basket):
- """ This function is called when the user chooses to add items from the main menu. It allows the user to input
- multiple items at once, delimited by commas. It only checks if an item is already in the list.
- """
- new_item_input = input("What items do you want to add to the basket? (separate items with commas) ")
- new_item_list = new_item_input.split(",") # this returns a list of all of the items separated by commas.
- # Loop through the list of items, and do some validation.
- for new_item in new_item_list:
- # This removes spaces from the outside of each item. It does not remove spaces inside items.
- # EG, if the user input the string literal " spam and eggs ", it would return "spam and eggs".
- new_item = new_item.strip()
- if new_item == "":
- # Here we ignore any items which aren't anything.
- pass
- elif new_item in current_basket.get_items():
- # Here we ignore any items which are arleady in the basket.
- print(new_item, "is already in the basket!")
- else:
- # Here we add valid items to the basket.
- print(new_item, "added to the basket!")
- current_basket.add_item(new_item)
- print() # Add an extra newline for formatting purposes.
- def do_remove_item(current_basket):
- """ This function is called when the user chooses to remove an item from the main menu. It validates the user's
- input, then sends the input to the basket object to remove.
- """
- while True:
- item_to_remove = input("What item do you want to remove? ")
- item_to_remove = item_to_remove.strip() # remove spaces from the ends so that comparison is easier
- try:
- # Here we're validating the input by trying to remove the item.
- current_basket.remove_item(item_to_remove)
- except ValueError:
- # 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
- # and ask again.
- print(item_to_remove, "is not in the basket!")
- else:
- # If the removal goes through properly, we tell the user and then skedaddle.
- print(item_to_remove, "removed from the basket!\n")
- return
- def do_replace_item(current_basket):
- """ This function is called when the user chooses to replace an item from the main menu. It validates the user's
- choices, then tells the basket object to do the replacement.
- """
- # a couple loop variables
- valid_replacee = False # if the user gives a valid item to replace, it wont ask for that again.
- valid_replacement = False # if the user gives a valid new item, it wont ask for that again.
- while True:
- if not valid_replacee: # we only ask them for an item to replace if we don't already have a valid one.
- item_to_replace = input("What item do you want to replace? ")
- item_to_replace = item_to_replace.strip() # remove any spaces so that comparisons are easier
- if item_to_replace not in current_basket.get_items():
- print(item_to_replace, " is not in the basket!")
- continue # go back to the top of the while loop
- valid_replacee = True
- if not valid_replacement: # we only ask them for an item to replace if we don't already have a valid one.
- new_item = input("What item to you want to exchange for " + item_to_replace + "? ")
- new_item = new_item.strip()
- if new_item in current_basket.get_items():
- print(new_item, "is already in the basket!")
- continue # return to the top of the while loop
- valid_replacement = True
- current_basket.replace_item(item_to_replace, new_item) # we let the basket class handle the replacement
- print("Replaced", item_to_replace, "with", new_item + "!\n")
- return
- # **NOTE: For this function we don't use the try...except method of validation because we want to validate the
- # **item to replace and the new item separately. If we just tried to send it to the basket object, it would only
- # **send one exception, plus it wouldn't complain about adding the same item to the basket twice.
- def do_main_menu(current_basket):
- """ This function presents a main menu to the user and validates their selection before sending it back to the
- caller.
- """
- print("What would you like to do with your", current_basket.get_type(), "basket?\n")
- # a list of the menu items available to the user.
- menu_items = [
- "Add items!",
- "Remove an item!",
- "Replace an item!",
- "Can you tell me about this basket?",
- "Can I switch to a different basket?",
- "Create a new basket!",
- "Quit!"
- ]
- # this loop will repeat until a valid input is given
- while True:
- # This prints out each option in the menu items list with a number in front of it.
- for index, item in enumerate(menu_items, 1):
- print("\t", str(index) + ")", item)
- # we already printed the prompt with the for loop above, so we just display a blank prompt for the input.
- menu_input = input("")
- # here we validate the user's selection
- try:
- menu_selection = eval(menu_input) # try to convert the input (which is a string) into an int
- except(NameError, TypeError):
- # if the input cannot be made into an int, the program jumps here. We display an error message, then
- # the program will just go back to the top of the while loop.
- print("You did not enter a valid menu selection. Please select a valid menu selection.\n")
- else:
- # this code is executed only if the input can be converted to an int.
- # first we make sure that the number they entered matches a menu selection.
- if 0 < menu_selection <= len(menu_items):
- # if the number is valid we return, which automatically breaks out of the while loop.
- return menu_selection
- else:
- print("The number you entered does not correspond to a menu item.\n")
- def main():
- """ This is the main function which is the base application which calls all the other functions and creates
- classes as needed.
- """
- print("Let's Make a Basket!\n")
- # First we make a list of baskets and set the "current basket" to the first item in the list (which currently
- # doesn't exist), but it will by the time we use it
- my_baskets = []
- current_basket_index = 0
- create_user_basket(my_baskets)
- running = True
- while running:
- menu_selection = do_main_menu(my_baskets[current_basket_index])
- # run the correct function based on the menu option selected previously
- if menu_selection == 7:
- running = False
- elif menu_selection == 6:
- create_user_basket(my_baskets)
- elif menu_selection == 5:
- current_basket_index = do_switch_basket(my_baskets, current_basket_index)
- elif menu_selection == 4:
- do_basket_info(my_baskets[current_basket_index])
- elif menu_selection == 3:
- do_replace_item(my_baskets[current_basket_index])
- elif menu_selection == 2:
- do_remove_item(my_baskets[current_basket_index])
- elif menu_selection == 1:
- do_add_item(my_baskets[current_basket_index])
- else:
- print("I have no idea how you got here, but why don't you start over?")
- return True
- # This is where the program begins. Everything occurs in the main() function, but we need to call it here
- # to get things started.
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement