[Tutor] list, tuple or dictionary
ADRIAN KELLY
kellyadrian at hotmail.com
Tue Nov 29 22:04:35 CET 2011
thanks guy, i was thinking of using a dictionary:- Stock_list = {"White Bread": 1.24, "Biscuits": 1.77, "Banana" : 0.23, "Tea Bags" : 2.37, "Eggs" : 1.23, "Beans" : 0.57}
how would i go about adding, for example tea and eggs to get a subtotal?
Adrian Kelly
1 Bramble Close
Baylough
Athlone
County Westmeath
0879495663
From: waynejwerner at gmail.com
Date: Tue, 29 Nov 2011 14:49:00 -0600
Subject: Re: [Tutor] list, tuple or dictionary
To: kellyadrian at hotmail.com
CC: tutor at python.org
On Tue, Nov 29, 2011 at 2:31 PM, ADRIAN KELLY <kellyadrian at hotmail.com> wrote:
i am trying to create a program that will allow users to enter items and their prices; should i be looking at a list, tuple or what?
The entering part isn't as important as how you want to display the data. For instance, here's a program that allows the user to input an unlimited amount of data (using Python 3.x):
while input("Enter q to quit, or an item: ").lower() not in ('q', 'quit', 'goodbye'):
input("Enter the price: ")
Of course it doesn't store the data, so it's pretty useless. But it does allow the user to input whatever they want.
If you wanted to simply create a collection of items you could do it as a list with alternating values:
inventory = ['Crunchy Frog', 4.13, 'Anthrax Ripple', 12.99999999999, 'Spring Surprise', 0.00]
for x in range(0, len(inventory)-1, 2): print(inventory[x], inventory[x+1])
Or as a list of tuples:
inventory = [('Norwegian Blue', 500.00), ('Slug', 500.00), ('Cage', 50.00)] for item in inventory: print(item[0], item[1])
Or a dictionary:
inventory = {'Spam':5.00, 'Spam on eggs':10.00, 'Spam on Spam':7.50} for item, price in inventory.items(): print(item, price)
Or if you wanted to get ridiculous, you could go with a list of classes:
class Item: def __init__(self, desc='', price=0.00): self.desc = desc
self.price = price def __repr__(self): return str(self) def __str__(self): return "{0} - {1}".format(self.desc, self.price)
inventory = [Item('Lumberjack', 5.5), Item('Tree', 50), Item('Flapjack', 0.5)]for item in inventory: print(item)
It just depends on how complex you want to get!
HTH,Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20111129/c3ce40c5/attachment-0001.html>
More information about the Tutor
mailing list