简体   繁体   中英

How do I add multiple items to a List in Python?

So I have a code that runs a Craigslist type of site, in theory. This is the code.

#Problem 4
choice = ()
while choice != 4:
    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 == 4:
        break

#Add an item
    if choice == 1:
        b = "bike"
        m = "microwave"
        d = "dresser"
        t = "truck"
        c = "chicken"
        itemType = raw_input("Enter the item type-b,m,d,t,c:")
        itemCost = input("Enter the item cost:")
        List = []
        List.extend([itemType])
        List.extend([itemCost])
        print List

The user should be able to input the choice of 1 enter their items, press 1 again and enter more items. How do I get the list to save without it overwriting the previous input?

First off, don't use List as a variable name. It is a built-in type in Python.

The reason why you are overwriting the previous input is because you are defining a new list every time a user enters 1. Define your list outside the scope of your conditional statements.

#Problem 4
itemList = []
choice = ()
while choice != 4:
    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 == 4:
        break

    #Add an item
    if choice == 1:
        b = "bike"
        m = "microwave"
        d = "dresser"
        t = "truck"
        c = "chicken"
        itemType = raw_input("Enter the item type-b,m,d,t,c:")
        itemCost = input("Enter the item cost:")
        itemList.append((itemType, itemCost))
        print itemList

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