Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Something went wrong
#1
This program is a simple shopping list that could also be used for TODOs or similar purposes. The program maintains a list of items in a file, and each item has:
·     name, price, priority (1, 2 or 3), whether it is required or completed
Users can choose to see the list of required items or completed items, including a total of the (estimated) price of all of those items. The lists will be sorted by priority.
Users can add new items and mark items as completed.
They can’t change items from completed to required.

Program Functionality Details:
Ensure that your program has the following features, as demonstrated in the sample output below.
Your program should:
·     display a welcome message with your name in it
·     display a menu for the user to choose from
·     return to the menu and loop until the user chooses to quit
·     error-check user inputs as demonstrated in the sample output
·     start by loading a CSV (Comma Separated Values) file of items that are in stock for hire;
a sample CSV file is provided for you
·     (when the user chooses list) display a neatly formatted list of all the required items with their prices lined up and priorities
·     (when the user chooses show completed) display a similarly formatted list of completed items
·     (when the user chooses add) prompt for the item’s name, price and priority, error-checking each of these, then add the item to the list in memory
·     (when the user chooses complete) display the same list of required items, then allow the user to choose one (error-checked), then change that item to completed
o  if no items are required, then a message should be displayed and the user returned to the menu
·     (when the user chooses quit) save the items to the CSV file, overwriting the file contents




MY CODE: 
import csv
import string
import operator
    
def load_csv():
    file_pointer = open("items.csv", 'r')
    return csv.reader(file_pointer, delimiter = ',')

def menu():
    menu_str = """Menu:
R - List required items
C - List completed items
A - Add new item
M - Mark an item as completed
Q - Quit """
    print(menu_str)
    
def get_input(valid_input):
    user_input = input(">>> ").upper()
    if user_input not in valid_input:
        print("Invalid input.")
        user_input = input(">>> ").upper()
    return user_input

print("Shopping list 1.0")
name = input("Please enter your name: ")
print("Welcome " + name + ".")

rowCount = sum(1 for row in load_csv())
print(rowCount, "items loaded from items.csv")

while True:
    menu()
    userChoice = get_input(["R", "C", "A", "M", "Q"])

    if userChoice == "R":
        print("Required items:")
        anyReq = False
        for row in load_csv():
            if "r" in row[3]:
                anyReq = True
                sortReq = sorted(load_csv(), key=operator.itemgetter(2))
                for number, item in enumerate(sortReq):
                    item_name = item[0]
                    item_price = float(item[1])
                    item_priority = item[2]
                    print(number, ". {} ${:.2f} ({})".format(item_name, item_price, item_priority))
                totalReq = sum(float(row[1]) for row in sortReq)
                print("Total expected price for", number+1 , "items: ${0:.2f}".format(totalReq))
                break
            if anyReq is False:
                print("No required items.")
                break
        print("Restarting menu...")

    if userChoice == "C":
        print("Completed items:")
        anyComp = False
        for row in load_csv():
            if "c" in row[3]:
                anyComp = True
                sortComp = sorted(load_csv(), key=operator.itemgetter(2))
                for number, item in enumerate(sortComp):
                    item_name = item[0]
                    item_price = float(item[1])
                    item_priority = item[2]
                    print(number, ". {} ${:.2f} ({})".format(item_name, item_price, item_priority))
                totalReq = sum(float(row[1]) for row in sortReq)
                print("Total expected price for", number+1 , "items: ${0:.2f}".format(totalReq))
                break
            if anyComp is False:
                print("No completed items.")
                break
        print("Restarting menu...")

    if userChoice == "A":
        itemName = input("Name: ")
        itemName = itemName.replace(" ", "")
        while itemName.isdigit() or itemName == "":
            print("Invalid input.")
            itemName = input("Name:")

        itemPrice = input("Price: $")
        itemPrice = itemPrice.replace(" ", "")
        while itemPrice.isalpha():
            print("Invalid input. Please enter a valid price.")
            itemPrice = input("Price: $")
        while float(itemPrice) < 0:
            print("Price stated must be equal to or more than $0.")
            itemPrice = input("Price: $")

        itemPriority = input("How important? Please rank in terms of 1, 2 or 3, with 1 being the lowest and 3 being the highest.")
        itemPriority = itemPriority.replace(" ", "")
        while itemPriority.isalpha():
            print("Invalid input. Please enter a valid number.")
            itemPriority = input("How important? Please rank in terms of 1, 2 or 3, with 1 being the lowest and 3 being the highest.")
        while itemPriority != "1" and itemPriority != "2" and itemPriority != "3":
            print("Priority must be larger than 0.")
            itemPriority = input("How important? Please rank in terms of 1, 2 or 3, with 1 being the lowest and 3 being the highest.")

        addNewItem = "{} ${:.2f} (priority {}) added to shopping list.".format(itemName, float(itemPrice), int(itemPriority))
        print(addNewItem)

        itemName = itemName + ","
        itemPrice = itemPrice + ","
        itemPriority = itemPriority + "," + "r"
        with open('items.csv', 'a') as addCSV:
            addCSV.writelines([itemName, itemPrice, itemPriority])
        print("Restarting menu...")

    if userChoice == "M":
        print("Required items:")
        anyReq = False
        for row in load_csv():
            if "r" in row[3]:
                anyReq = True
                for number, item in enumerate(load_csv()):
                    item_name = item[0]
                    item_price = float(item[1])
                    item_priority = item[2]
                    print(number, ". {} ${:.2f} ({})".format(item_name, item_price, item_priority))
                totalReq = sum(float(row[1]) for row in load_csv())
                print("Total expected price for", number+1 , "items: ${0:.2f}".format(totalReq))
                break
            if anyReq is False:
                print("No required items.")
                break

        markItem = input("Enter the number of an item to be marked as completed.")
        while markItem.isalpha():
            print("Invalid input; please enter a number.")
            markItem = input("Enter the number of an item to be marked as completed.")
        while int(markItem) < 0 or int(markItem) > number+1:
            print("Invalid item number.")
            markItem = input("Enter the number of an item to be marked as completed.")

##        with open ('items.csv', 'r') as item_file:
##            readCSV = item_file.read()
##            itemLine = [i.split(",") for i in readCSV.split("\n")]
##        itemLine[int(markItem)][3] = "c"
##        itemLine = "\n".join([",".join(item) for item in itemLine])
##
##        with open ('items.csv', 'a') as editCSV:
##            editCSV.write(itemLine)
            
##        for row in load_csv():
##            if "r" in row[3]:
##                anyReq = True
##                print("{} marked as completed.".format([int(markItem)][0]))

        print("Restarting menu...")

    if userChoice == "Q":
        rowCount = sum(1 for row in load_csv())
        print(rowCount, "items saved to items.csv")
        break 

print("Program ended.")
Reply


Messages In This Thread
Something went wrong - by infernoblaze - Dec-09-2016, 12:26 PM
RE: Something went wrong - by stranac - Dec-09-2016, 12:33 PM
RE: Something went wrong - by infernoblaze - Dec-09-2016, 12:45 PM
RE: Something went wrong - by nilamo - Dec-09-2016, 07:26 PM
RE: Something went wrong - by infernoblaze - Dec-12-2016, 11:22 PM
RE: Something went wrong - by nilamo - Jan-04-2017, 03:17 PM
RE: Something went wrong - by nilamo - Dec-14-2016, 04:14 PM
RE: Something went wrong - by infernoblaze - Dec-16-2016, 02:06 AM
RE: Something went wrong - by Ofnuts - Dec-16-2016, 08:46 AM
RE: Something went wrong - by infernoblaze - Jan-04-2017, 02:16 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020