理论上,我有一个运行Craigslist类型网站的代码。这是代码。
#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
用户应该能够输入1选择输入项目,再次按1并输入更多项目。如何在不覆盖先前输入的情况下保存列表?
答案 0 :(得分:1)
首先,请勿使用List
作为变量名称。它是Python中的内置类型。
您要覆盖之前输入的原因是每次用户输入时定义新列表1.在条件语句范围之外定义列表。
#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