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
#2
infernoblaze Wrote:Something went wrong
And that something is?
You need to show us the error you get, or the expected vs. actual output
Reply
#3
I can't seem to get A(adding an item) to work. I've been trying to change the code, but i just can't crack my head to do it, i am stuck.
Reply
#4
Do you get an error? What is it?

Or are you getting something written to the file, and it just isn't what you expected?

Help us out here.
Reply
#5
addItem.writerows(data)
_csv.Error: iterable expected, not float

it just says that, and no matter what number i type, 1-3(ranks), it just ended up with error, thus, can't add any item, is there anyone can help me check it out?
Reply
#6
Try adding a print(data) right before that. It should be an iterable, not a float.
Reply
#7
print(data) to where?
Reply
#8
(Dec-16-2016, 02:06 AM)infernoblaze Wrote: print(data) to where?

To the command prompt in which you started your script.

If you double-click the script to start it, that will make the debugging rather difficult
Unless noted otherwise, code in my posts should be understood as "coding suggestions", and its use may require more neurones than the two necessary for Ctrl-C/Ctrl-V.
Your one-stop place for all your GIMP needs: gimp-forum.net
Reply
#9
what? i still don't get it?
Reply
#10
(Dec-12-2016, 11:22 PM)infernoblaze Wrote: addItem.writerows(data)
_csv.Error: iterable expected, not float

it just says that, and no matter what number i type, 1-3(ranks), it just ended up with error, thus, can't add any item, is there anyone can help me check it out?

You've got an error when trying to write whatever "data" is (which isn't in your original source, so we're just guessing as to how to help).  Right before that line (wherever it is), add print(data) so you can see exactly what it is you're trying to write to the file.
Reply


Forum Jump:

User Panel Messages

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