Python Forum

Full Version: project help
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
The inventory of the items for sale is growing and will continue to do so. It’s now no
longer practical to change the code’s internals every time an item is added (or deleted) from the system.
Instead, another group will provide the inventory items in a file that the program will read and use to populate
the category items. Each category will have its own file that contains the list of items in that category.
For example, instead of only displaying three items in the book category, a list of book descriptions and their
prices will be given in a text file (-.txt). The program will read and use that file to build its internal “book_list”
(list or tuple) and book category display menu. The items will be given one per line, each line consisting of the
item description, followed by the item’s price. A comma (“,”) will separate the description from the price. A
sample -.txt file for the electronics category follows:
LinkSys Router, 49.95
HP Laptop, 350.00
Altec Lansing Speakers, 195.95
EyePhone 10,795.00
First Alert Smoke Alarm, 29.95
LG 55 UDTV,350.00
Sony Prtable Radio, 15.00
Dell All-in-One PC, 495.00
Brother Laser Printer, 99.00
The number of items in each category will vary, although they will all fit on one screen (assume no more than
20 items per category). An item menu for clothing would look like this:
<start menu>
Clothing menu
Select from the following items, display cart, or checkout:
No. Item Description Price
=== =========================== ========
1 - Vasque Hiking Boots $ 109.00
2 - Wool Hat $ 14.00
3 - Pants $ 39.95
4 - Wrangler Jeans $ 24.50
5 - Armani Suit $ 800.00
6 - Nike T-shirt $ 19.00
7 - New Balance Trail Runners $ 69.95
8 - Gore-Tex Gloves $ 39.00
9 - North Face Fleece Jacket $ 89.95
10 - Nationals Logo Sweatshirt $ 49.00
d - display cart contents
x - return to category menu
Enter Selection (1 to 10, "d", or "x"):
<end menu>
The number of categories for this assignment will remain at three. One file for each category will be provided
for testing, although the GTA will use other files for evaluating the submissions. The files will be named:
books.txt
electronics.txt
clothing.txt
Additional instructions will be given on how your program will access those files. For now, I suggest you
assign a variable name inside your program for each file and assign the filename to that string. Then open the
file by referring to that string. For example:
infile = ‘C:/Files/books.txt’
fi = open(infile,"r")
itemfile = fi.readlines() # items = list of item descriptions + price
‘C:/Files/books.txt’ is the fully qualified name of the file as it exists on your computer. “books.txt” should be
the same, but the “C:/Files/” is a prefix that will be specific to your system. As an alternative, you can prompt
the user to give the file name as an input string and use that. I will be showing a function to handle some of this
later today or during the next class.
Besides using the basic open and read functions (“readlines()” is suggested), you will have to use the string
“split” method shown in class to separate the item description and price and assign them to two separate
variables. You should also use the “strip” method to remove extraneous leading and trailing spaces and newline
characters.

import os
more_carts = "y"
carts =0
cart_items = 0
cart_cost = 0.0
session_carts = 0
session_items = 0
session_cost = 0.0
menu = """
1 - Books
2 - Electronics
3 - Clothes
d - show cart contents
c - Checkout

Select one of the categories or checkout (1 – 3 or ‘c’ or 'd'):
"""

while more_carts == "y":
    books_items = 0
    books_cost = 0.0
    elect_items = 0
    elect_cost = 0.0
    clothing_items = 0
    clothing_cost = 0.0
    cart = []
    book_list = [["Origin",19.95], ["Grant", 24.50], ["Prairie Fires", 18.95]]
    elect_list = [["HP Laptop",429.50],["EyePhone 10",790.00],["Bose 20 Speakers",220.00]]
    clothing_list = [["T-shirt", 9.50],["Shoes", 45.00],["Pants", 24.00]]

    more_items = "y"
    while more_items == "y":
        os.system('cls')
        category = input(menu)
        if category == "c":
            break
        elif category == "d":
            print("shopping cart ",cart)
        elif category not in "123":
            print("Invalid category selected")
            continue
        
        item_pic = " "
        if int(category) == 1:
            item_pic = " "
            while item_pic != "x":
                os.system('cls')
                item_pic = input(book_menu)
                if item_pic in("1","2","3"):
                    response = input("Add "+book_list[int(item_pic)-1][0]+" y/n? ")
                    if response == "y":
                        cart.append(book_list[int(item_pic) -1])
                        print("shopping cart = ", cart)
                    else:
                        continue
                elif item_pic == "d":
                    print("shopping cart = ",cart)
                elif item_pic != "x":
                    print("Invalid item selected")
                    
        elif category == "2":
            item_pic = " "
            while item_pic != "x":
                os.system('cls')
                item_pic = input(elect_menu)
                if item_pic in("1","2","3"):
                    response = input("Add "+elect_list[int(item_pic) -1][0]+" y/n? ")
                    if response == "y":
                        cart.append(elect_list[int(item_pic) -1])
                        print("shopping cart = ", cart)
                    else:
                        continue    
                elif item_pic == "d":
                    print("shopping cart = ",cart)
                elif item_pic != "x":
                    print("Invalid item selected")
                    
        elif category == "3":
            item_pic = " "
            while item_pic != "x":
                os.system('cls')
                item_pic = input(clothing_menu)
                if item_pic in("1","2","3"):
                    response = input("Add "+clothing_list[int(item_pic) -1][0]+" y/n? ")
                    if response == "y":
                        cart.append(clothing_list[int(item_pic) -1])
                        print("shopping cart = ", cart)
                    else:
                        continue
                elif item_pic == "d":
                    print("shopping cart = ",cart)
                elif item_pic != "x":
                    print("Invalid item selected")
                    
    if category == "c":
        print("\nCheckout Selected.....")

    if len(cart) > 0:
        cart_total_cost = 0.0
        print("\n\t{0:20s}\t\t{1:4s}".format("items", "cost"))
        print("\t{0:20s}\t\t{1:9s}".format("====================","========="))
        for items in cart:
            print("\t{0:20s}\t\t${1:8.2f}".format(items[0],items[1]))
            cart_total_cost += items[1]
        print("\nTotal number of items: {0:5d}    cost: ${1:8.2f}".format(len(cart), cart_total_cost))
        session_carts += 1
        session_items += len(cart)
        session_cost +=cart_total_cost
    else:
        print("\nCart is empty\n")
        
more_carts = input("\nAre there more carts to process (y/n)?\n")
print("\n\n\tTotal number of carts: ", session_carts)
print("\tTotal number of items: ",session_items)
print("\tTotal cost of items: $%8.2f" %(session_cost))
input ("\n\nHit Enter to end program")
What's your question?
You are supposed to read inventory information from a file. Where do you open a file? Where do you read from it?

Keep your old code, but start fresh with a new program. The having the old code in your editor will just cause confusion and slow progress at this point. Write a program that opens a file and read one inventory item. Print the item out to verify you read it correctly. Congrats!

Modify your program to print out the item description and price separately. Eventually you will need to do this. Got that to work? Congrats on accomplishing another step.

You'll need the ability to read multiple items from the file. Can your program read two items? Change your program and verify. Can your program read all the items in the file without knowing how many there will be? Congrats again, you just read in a category! Can your program read two or three categories? Test and verify. I think the assignment says you need to read three categories. If you can do that you are almost done!

Now you can look at your old program. See where you hard coded the categories? How do you replace that with your new program that reads inventory from a file? If you used functions or classes in your "read_inventory" program it will be a lot easier to integrate the two programs. Add the read inventory functionality to your old shopping program. Print out one of the catefories. Does it look correct?

This is an easy assignment. It includes hints and even code about how you should read the information from the file (readlines) and how to beak the lines into a description and a price (split). Focus on one small step at a time and run a test to verify each step is working before moving on to the next. That should produce steady progress and make you feel confident.
I'm stuck on creating and formatting menu. was able to make a dictionary.
I'm not sure how to format it to look like this
No. Item Description Price
=== =========================== ========
1 - Vasque Hiking Boots $ 109.00
2 - Wool Hat $ 14.00
3 - Pants $ 39.95
4 - Wrangler Jeans $ 24.50
5 - Armani Suit $ 800.00
6 - Nike T-shirt $ 19.00
7 - New Balance Trail Runners $ 69.95
8 - Gore-Tex Gloves $ 39.00
9 - North Face Fleece Jacket $ 89.95
10 - Nationals Logo Sweatshirt $ 49.00
d - display cart contents
do i use a for loop for creating this menu?
Why didn't you post the code that reads the dictionaries? Would have saved me a lot of typing.

Isn't the menu just a bunch of print statements? For description, price in category.items() print something?
infile = "books.txt"
fi = open(infile,"r")
book_item = {}
for line in fi:
    list1 = line.split(",")
    des = list1[0]
    price = list1[1]
    book_item[des] = price.strip()
fi.close()

infile1 = "electronics.txt"
fi = open(infile1,"r")
electronic_item = {}
for line in fi:
    list1 = line.split(",")
    des = list1[0]
    price = list1[1]
    electronic_item[des] = price.strip()
fi.close()

infile2 = "clothing.txt"
fi = open(infile1,"r")
clothing_item = {}
for line in fi:
    list1 = line.split(",")
    des = list1[0]
    price = list1[1]
    clothing_item[des] = price.strip()
fi.close()
this the program that create a new list
I get carpal tunnel just looking at that. Why did you write the same code three times? Event though the assignment said the number of categories will remain at 3, why not write your program in such a way that it would be easy to expand to have more categories. A good start is writing a function that reads the categories. You would call it once for each file. 12 lines instead of 27. Easier to understand and designed to be upgradeable.

Plus it would be your first function! You'll probably want your menu code to be a function.