没有正确附加到列表?

时间:2015-05-24 17:32:17

标签: python

def addItem():
    flavorsMenu()
    flavor = int(input("> "))
    validateData(flavor)
    if validateData(flavor) == "f":
        print("Sorry, that was an invalid choice.")
        return None
    else:
        print("How many would you like to buy? (1-10) ")
        qty = int(input("> "))
        if qty <= 0 or qty > 10:
            print("Invalid number, please try again")
        else:
            quantityList.append(qty)
            itemsList.append(flavors[flavor - 1])
            print("You have added", qty, str(flavors[flavor - 1]) + "(s) to your list.")
            return flavor

我把返回的味道看看是否会有所帮助,但事实并非如此,我已将所有内容定义在顶部

flavors = ["Thin Mints", "Tagalongs", "Samoas", "Lemon Chalet Cremes", "Dulce de Leche", "Sugar Free Chocolate Chip", "Do-Si-Dos", "Trefoil"]

但是当我输入5时,它给了我薄薄的薄荷糖1.当我进入4时,它再次给我薄薄的薄荷糖。当我输入3时,它会给我tagalongs。

为什么会这样?

1 个答案:

答案 0 :(得分:0)

我已将您的代码编写为:

flavors = ["Thin Mints", "Tagalongs", "Samoas", "Lemon Chalet Cremes", "Dulce de Leche", "Sugar Free Chocolate Chip", "Do-Si-Dos", "Trefoil"]

quantityList = []
itemsList = []

def addItem():
    flavor = int(input("> "))
    print("How many would you like to buy? (1-10) ")
    qty = int(input("> "))
    if qty <= 0 or qty > 10:
        print("Invalid number, please try again")
    else:
        quantityList.append(qty)
        itemsList.append(flavors[flavor - 1])
        print("You have added", qty, str(flavors[flavor - 1]) + "(s) to your list.")
        return flavor

print flavors[ addItem() -1 ]

它工作正常。