Question

In Python and in one file please. (Simple functions with an expressions) Create a function called...

In Python and in one file please. (Simple functions with an expressions) Create a function called load_inventory(filename). The filename argument in this case specifies the name of a file that contains all the inventory/product information for the store, including product names, descriptions, prices, and stock levels. This function should clear any information already in the product list (i.e., a fresh start) and then re-initialize the product list using the file specified by the filename argument. You can structure your file any way you like, but a suggested line-by-line structure like given below: Desktop Computer 3Ghz, 16GB RAM, 250GB Hard Drive 1200 10 Laptop Computer 2.5Ghz, 8GB RAM, 128GB Hard Drive, 15" Screen 1500 15 Add another function to the a4.py file called save_inventory(filename). This function should save all the product list information into the file with the specified name. It should also overwrite any data that is already in the file. Once you have defined both the save and load inventory functions, you will be able to load a stored information, perform some changes using the other functions, then save those changes back to the file so they are remembered when the program restarts and the file is loaded again. Add another function to the a4.py file called add_new_product(name, desc, price, stock). This function accepts four arguments representing the information for a new product. It should add that new product to the store’s product list only if no other product in the store’s product list has the same name (case should be ignored, so “Tablet” and “tablet” would be considered the same name). This will ensure the names of products in the store are unique, which will be important to remove ambiguity in other functions (e.g., one that removes products by name). This function must return True to indicate the product was successfully added or False to indicate the product was not added. Add another function to the a4.py file called remove_product(name). This function must go through the store’s product list and remove a product from the list if that product’s name matches the given name argument (again, this should not be case sensitive). The function should return True to indicate a product was removed and False if a product was not removed. Add another function to the a4.py file called add_product_stock(name, units). This function must search through the store’s product list to find a product with the matching name. If a matching product is found, the stock of that product in the store should be increased by the given number of units. The function should return True to indicate the stock level of a product was updated and False to indicate no updates were made (e.g., if a product was not found with that name). Add another function to the a4.py file called sell_product(name, units). This function must search through the store’s product list to find a product with the matching name. If a matching product is found and the stock level of that product is at least the number of units specified (i.e., the store has that many units available to sell), then the stock level of that product should be decreased by the specified number of units. This function must return True to indicate that a product was found and the stock was updated. If a product with that name is not found or there are not enough units in stock to complete the sale, the function must return False. Add another function to the a4.py file called list_products(keyword). This function will search through the list of products and print out those that match the given keyword argument. If the keyword is “*”, then all products should be considered a match (essentially, this prints the entire store inventory). Otherwise, a product should match the keyword if that keyword is contained either in the product name or the product description (not case sensitive, “tablet” should match “Tablet”, and “TABLET”, etc.). The printout should format the product information in an easy to read fashion that includes the name, description, price and number of units in stock. Add a final function to the a4.py file called main(). This function must print out a menu with the 9 options detailed in the table below and allow the user to repeatedly enter choices until they chose to quit. An example of what the output might look like here: his is example output created by the main() function when it is run. The inventory.txt file that is loaded in this example is included on the assignment. You can use it as a starting point for your own file or create your own by adding products through the menu. Choose an option below to proceed: 1. Load Inventory 2. Save Inventory 3. Add New Product 4. Add Product Stock 5. List Products 6. Search Products 7. Sell Products 8. Remove Product 9. Quit >5 There are no products that match. Choose an option below to proceed: 1. Load Inventory 2. Save Inventory 3. Add New Product 4. Add Product Stock 5. List Products 6. Search Products 7. Sell Products 8. Remove Product 9. Quit >1 Enter the file name to load from:inventory.txt Choose an option below to proceed: 1. Load Inventory 2. Save Inventory 3. Add New Product 4. Add Product Stock 5. List Products 6. Search Products 7. Sell Products 8. Remove Product 9. Quit >5 1. Desktop Computer, 3Ghz, 16GB RAM, 250GB Hard Drive, $1200.0, 10 units in stock 2. Laptop Computer, 2.5Ghz, 8GB RAM, 128GB Hard Drive, 15" Screen, $1500.0, 15 units in stock

0 0
Add a comment Improve this question Transcribed image text
Answer #1

#Code is written to work in python version 3

#Save to a file of .py extension and execute it with python <ilename.py>

# Ex: python inventory.py

class Inventory():

    def __init__(self):

        self.full_data = {}

        self.prod_available = lambda name: str(name).lower() in self.full_data.keys()

    def load_inventory(self, filename):

        with open(filename)as fobj:

            data = fobj.readlines()

        for row in data:

            inv_data = [col.strip() for col in row.split(",")]

            if inv_data:

                self.full_data[inv_data[0].lower()] = inv_data

        print("Loaded data from file %s"%filename)

    def save_inventory(self, filename):

        with open(filename, "w") as fobj:

            for data in self.full_data.values():

                wdata = ", ".join(data)

                fobj.write(wdata+"\n")

    def add_new_product(self, name, desc, price, stock):

        if not self.prod_available(name):

            if not stock.isnumeric():

                print("Stock val should be an integer; failed adding product")

                return False

            self.full_data[name.lower()] = [name, desc, price, stock]

            return True

        else:

            print("Product %s already available"%name)

            return False

    def remove_product(self, name):

        if not self.prod_available(name):

            print("Provided product %s not in the list"%name)

            return False

        else:

            del self.full_data[str(name).lower()]

    def add_product_stock(self, name, units):

        if self.prod_available(name):

            data = self.full_data[str(name).lower()]

            data[-1] = str(int(data[-1]) + units)

        else:

            print("Provided product %s not in the list"%name)

            return False

    def sell_product(self, name, units):

        if self.prod_available(name):

            data = self.full_data[str(name).lower()]

            if units <= int(data[-1]):

                data[-1] = str(int(data[-1]) - units)

                return True

            else:

                print("Units not sufficient to sell")

              return False

        else:

            print("Provided product %s not in the list"%name)

            return False

    def list_products(self, keyword):

        found_data = []

        if keyword == "*":

            found_data = self.full_data.values()

        else:

            for vals in self.full_data.values():

                if str(keyword).lower() in vals[0].lower() or str(keyword).lower() in vals[1].lower():

                    found_data.append(vals)

        for id_, row in enumerate(found_data, 1):

            print("%d. %s units in stock"%(id_, ", ".join(row)))

def print_options():

    print("""

    1. Load Inventory

    2. Save Inventory

    3. Add New Product

    4. Add Product Stock

    5. List Products

    6. Search Products

    7. Sell Products

    8. Remove Product

    9. Quit""")

def main():

    obj = Inventory()

    while True:

        print_options()

        val = str(input("Enter an option value: "))

        if val is "1":

            filename = input("Enter filename to load inventory: ")

            obj.load_inventory(filename)

        elif val is "2":

            filename = input("Enter filename to save inventory to: ")

            obj.save_inventory(filename)

        elif val is "3":

            name = input("Enter product name: ")

            desc = input("Enter product description: ")

            price = input("Enter price: ")

            stock = input("Enter no. of units: ")

            obj.add_new_product(name, desc, price, stock)

        elif val is "4":

            name = input("Enter product name: ")

            stock = input("Enter no. of units to add: ")

            if not stock.isnumeric():

                print("Stock should be an integer.")

            else:

                obj.add_product_stock(name, int(stock))

        elif val is "5":

            obj.list_products("*")

        elif val is "6":

            name = input("Enter name to list matching products: ")

            obj.list_products(name)

        elif val is "7":

            name = input("Enter name to sell products: ")

            stock = input("Enter units to sell: ")

            if not stock.isnumeric():

                print("Stock must be an integer to sell")

            else:

                obj.sell_product(name, int(stock))

        elif val is "8":

            name = input("Enter name to remove a product: ")

            obj.remove_product(name)

        elif val is "9":

            break

        else:

            print("Invalid option!!")

if __name__ == "__main__":

    main()

Add a comment
Know the answer?
Add Answer to:
In Python and in one file please. (Simple functions with an expressions) Create a function called...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • In Python and in one file please. (Simple functions with an expressions) Create a function called load_inventory(filenam...

    In Python and in one file please. (Simple functions with an expressions) Create a function called load_inventory(filename). The filename argument in this case specifies the name of a file that contains all the inventory/product information for the store, including product names, descriptions, prices, and stock levels. This function should clear any information already in the product list (i.e., a fresh start) and then re-initialize the product list using the file specified by the filename argument. You can structure your file...

  • I JUST NEED HELP WITH DISPLAY PART! please help! thanks in advance // This function saves...

    I JUST NEED HELP WITH DISPLAY PART! please help! thanks in advance // This function saves the array of structures to file. It is already implemented for you. // You should understand how this code works so that you know how to use it for future assignments. void save(char* fileName) { FILE* file; int i; file = fopen(fileName, "wb"); fwrite(&count, sizeof(count), 1, file); for (i = 0; i < count; i++) { fwrite(list[i].name, sizeof(list[i].name), 1, file); fwrite(list[i].class_standing, sizeof(list[i].class_standing), 1, file);...

  • Question: File response. You must create a program called “Assigment_Mod9.cpp” that allow to manage the inventory...

    Question: File response. You must create a program called “Assigment_Mod9.cpp” that allow to manage the inventory of a store. The program must have a menu that allow to perform the following three actions: Add a new item Remove an item Replicate n times and existing item The program must have two dynamic arrays: one for store the name of the product and other to store the price of the product. The size of each array must be of the same...

  • PROBLEM 3 Rewrite Program 2. This is you must use keyword arguments to pass number of kWh and customer type to the bill_calculator function when it is called. Save your Python program in a file named Lab07P3.py. Submit the file to Blackboard for cred

    Problem 3  Rewrite Program 2.  This is you must use keyword arguments to pass number of kWh and customer type to the bill_calculator function when it is called. Save your Python program in a file named Lab07P3.py.  Submit the file to Blackboard for credit.This is what i wrote for prgram 2:():     kwh = (())     cus = (())     cus.upper()     bill_calculator(kwhcus) (kwhcus):     kwh <= cus == :         price = kwh * kwh > cus == :         price = * + ((kwh - ) * )     kwh <= cus == :         price = kwh * kwh > cus == :         price = * + ((kwh - ) * )     (.format(price))

  • In python Attached is a file called sequences.txt, it contains 3 sequences (one sequence per line)....

    In python Attached is a file called sequences.txt, it contains 3 sequences (one sequence per line). Also attached is a file called AccessionNumbers.txt. Write a program that reads in those files and produces 3 separate FATSA files. Each accession number in the AccessionNumbers.txt file corresponds to a sequence in the sequences.txt file. Remember a FASTA formatted sequence looks like this: >ABCD1234 ATGCTTTACGTCTACTGTCGTATGCTTTACGTCTACTGACTGTCGTATGCTTACGTCTACTGTCG The file name should match the accession numbers, so for 1st one it should be called ABCD1234.txt. Note:...

  • // READ BEFORE YOU START: // You are given a partially completed program that creates a...

    // READ BEFORE YOU START: // You are given a partially completed program that creates a list of students for a school. // Each student has the corresponding information: name, gender, class, standard, and roll_number. // To begin, you should trace through the given code and understand how it works. // Please read the instructions above each required function and follow the directions carefully. // If you modify any of the given code, the return types, or the parameters, you...

  • Expected submission: 1 Python file, Graph_Data.py Make a file called Graph_data Inside this file create 3...

    Expected submission: 1 Python file, Graph_Data.py Make a file called Graph_data Inside this file create 3 functions: 1.) BarGraph: This function should take 5 parameters, X-axis data, y-axis data, X-axis label, y-axis label, title. It will create a bar graph using the above data and display it. 2.) Line Graph: This function is the same as above, except with a line graph instead of a bar graph 3.) SaveGraph: This function is the same as BarGraph, except it saves the...

  • Write a menu based program implementing the following functions: (0) Write a function called displayMenu that...

    Write a menu based program implementing the following functions: (0) Write a function called displayMenu that does not take any parameters, but returns an integer representing your user's menu choice. Your program's main function should only comprise of the following: a do/while loop with the displayMenu function call inside the loop body switch/case, or if/else if/ ... for handling the calls of the functions based on the menu choice selected in displayMenu. the do/while loop should always continue as long...

  • I need this python program to access an excel file, books inventory file. The file called...

    I need this python program to access an excel file, books inventory file. The file called (bkstr_inv.xlsx), and I need to add another option [search books], option to allow a customer to search the books inventory, please. CODE ''' Shows the menu with options and gets the user selection. ''' def GetOptionFromUser(): print("******************BookStore**************************") print("1. Add Books") print("2. View Books") print("3. Add To Cart") print("4. View Receipt") print("5. Buy Books") print("6. Clear Cart") print("7. Exit") print("*****************************************************") option = int(input("Select your option:...

  • Create a Python script file called hw12.py. Add your name at the top as a comment,...

    Create a Python script file called hw12.py. Add your name at the top as a comment, along with the class name and date. Ex. 1. a. Texting Shortcuts When people are texting, they use shortcuts for faster typing. Consider the following list of shortcuts: For example, the sentence "see you before class" can be written as "c u b4 class". To encode a text using these shortcuts, we need to perform a replace of the text on the left with...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT