简体   繁体   中英

Input User Inputs into a pre-defined list in Python

I am new to programming and am trying to update a pre-established list based upon user input in Python 2.5.

Here is exactly what I am trying to do:

I have various items that a user must choose from...let's use the following as an example:

item1 = [1,2,3,4]
item2 = [2,3,4,5]

I have the user choosing which item by using raw_input:

item_query = raw_input("Which item do you want?: ")

Once they have chosen their appropriate item, I want to place the appropriate item (along with the items contained in that respective list) into a blank list that will maintain that user's inventory:

user_inventory = []

Can anyone show me how to do this?

you should use a dictionary where the keys are the input you expect the user to enter

items = {"1":[1,2,3,4],"2":[2,3,4,5]}
user_inventory = []
while True:
   item = raw_input("Which Item would you like?")
   if item == "" or item.lower() == "q" or item.lower() == "quit":
       #user is done entering items
       break
   if item in items:
       #this is a little dicey since it is actually the same list, not a copy of the list
       user_inventory.append(items[item]) #you may want to insert a copy of the list instead
   else:
       print "Unknown Item:%s"%item

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM