0

I have a text file that says the following:

eggs,2.99
bacon,4.99
beer,5.96
raisins,3.81
oatmeal,4.13
lollipop,0.99
mints,1.13

Then I have the following code that asks which item they want and if it's an item it prints work.

import os, time
f = open("Products.txt", "r")
def choose():
    itemlist = []
    for line in f:
        parts = line.split(",")
        item = parts[0]
        price = parts[1]
        itemlist.append(parts[0])
        print '{:<15} {:>2}'.format(item, price)
    print("\nplease choose an item")
    print itemlist
    answer = raw_input()
    if answer in itemlist:
        print("WORK")

choose()

The program is meant to be like a cash register where you choose an item but I want for the price to be saved when an item is chosen. So if multiple items are set, it will add the price. I don't know how to find the price when they enter an item so I want to find a way to assign for instance "eggs" to its price.

1 Answer 1

1

So good you know about data structures however for this it would be better to use a dictionary.

import os, time
f = open("Products.txt", "r")

def choose():
    items = {}
    for line in f:
        item, price = line.split(",")
        items[item] = parts[price]
        print '{:<15} {:>2}'.format(item, price)
    print("\nplease choose an item")
    print itemlist
    answer = raw_input()
    if answer in items.keys():
        print("WORK")

choose()

Now why is this better? Because you can easily reassign (ie items["eggs"] = 1.05)

https://docs.python.org/2/tutorial/datastructures.html

Sign up to request clarification or add additional context in comments.

1 Comment

To make it a bit more readable, unpack the item and price when you split the line ... item, price = line.split(","); items[item] = price. And if answer in items.keys() can/should be if answer in items. Aaaannnnddd what is itemlist?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.