I’m trying to read from a simple text file that looks like this:
11
eggs
1.17
milk
3.54
bread
1.50
coffee
3.57
sugar
1.07
flour
1.37
apple
.33
cheese
4.43
orange
.37
bananas
.53
potato
.19
What I’m trying to do is ask an input for a file name such as “milk” than to print the price of that. I am trying to use dictionaries.
Here is my code:
def main():
key = ''
infile = open('shoppinglist.txt', 'r')
count = infile.readline()
groceries = {}
print('This program keeps a running total of your shopping list.')
print('Use \'EXIT\' to exit.')
grocery = input('Enter an item: ')
for line in infile:
line = line.strip()
if key == '':
key = line
else:
groceries[key] = line #maybe use here float(line) instead
key = ''
print ('Your current total is $'+ groceries[grocery])
main()
EXPECTED OUTPUT
This program keeps a running total of your shopping list.
Use ‘EXIT’ to exit.
Enter an item: eggs
Your current total is $1.17
Enter an item: bread
Your current total is $3.00
Enter an item: sugar
Your current total is $4.07
Enter an item: EXIT
Your final total is $4.07
Here you have. You already had a pretty ready code.
Look at the diferences:
-You were overwritting
groceries-you were not reading the value from the dictionary
-In python < 3x you shoud use raw_input instead of input. If you are in py3k input is OK
-Also you do not need parenthesis for print in py2.x. You do in py3k
-Maybe the only bizarre thing for a homework here is the use of % in print. It means that %s will be substituted by the string after the last % sign
-Be careful because cost of groceries are actually strings so you can not make mathematical operations with them. First you should convert them to floats.
For several inputs use (not tested, py3k code, remember to convert costs to floats before):