Reputation: 75
I'm not sure how to take user inputs and add it to a list by mapping based on item types.
In the following code example, after choice one is selected, user is prompted to enter item type, which is a single letter (b
, m
, d
, t
,c
).
Once user enters that letter and then the cost, I need to store in a list.
For example, if you enter b
then 10,in the list it should come out as [(Bike, 10)]^ and not
[(b, 10)]`.
I'm not even sure how to figure this out or attempt to. Also, sorry for the poor wording in title. I'm very new to this and was not sure how to word the question.
Code:
while True:
print "1. Add an item."
print "2. Find an item."
print "3. Print the message board."
print "4. Quit."
choice = input("Enter your selection: ")
if choice == 1:
item = raw_input("Enter the item type-b,m,d,t,c:")
cost = raw_input("Enter the item cost:")
elts = []
elts.append([item,cost])
if choice == 4:
print elts
break
Upvotes: 1
Views: 2123
Reputation: 4021
Use dictionaries. This is an example on how to use them for this case:
elts = []
items = {
'b': 'Bike',
'm': 'Motorcycle',
'd': 'Dodge',
't': 'Trailer',
'c': 'Car',
}
while True:
print "1. Add an item."
print "2. Find an item."
print "3. Print the message board."
print "4. Quit."
choice = input("Enter your selection: ")
if choice == 1:
item = raw_input("Enter the item type-b,m,d,t,c:")
cost = raw_input("Enter the item cost:")
elts.append([items[item],cost])
if choice == 4:
print elts
break
Output would be like:
1. Add an item.
2. Find an item.
3. Print the message board.
4. Quit.
Enter your selection: 1
Enter the item type-b,m,d,t,c:b
Enter the item cost:30
1. Add an item.
2. Find an item.
3. Print the message board.
4. Quit.
Enter your selection: 1
Enter the item type-b,m,d,t,c:c
Enter the item cost:40
1. Add an item.
2. Find an item.
3. Print the message board.
4. Quit.
Enter your selection: 4
[['Bike', '30'], ['Car', '40']]
Upvotes: 2