写一个循环,并将它们存储在一个列表中。在这里,一个while循环可能比较谨慎ingredients = []
while True:
name = raw_input("Name is your ingredient: ")
quantity = int(raw_input("What is the quantity of this ingredient: "))
unit = raw_input("What is the unit of your ingredient: ")
ingredients.append((name, quantity, unit))
cont = raw_input("Continue adding ingredients? [y/n]")
if not cont.lower() in ("y", "yes"):
break
代码将要求您想要的东西,并在每次迭代后将它们作为三元组追加到列表中。现在,一旦您完成了(通过回答除y或yes之外的任何问题),您将拥有一个包含三个元组的列表(ingredient name, ingredient quantity, ingredient unit)。
演示:Name is your ingredient: Flour
What is the quantity of this ingredient: 7
What is the unit of your ingredient: dl
Continue adding ingredients? [y/n]y
Name is your ingredient: Butter
What is the quantity of this ingredient: 50
What is the unit of your ingredient: gr
Continue adding ingredients? [y/n]y
Name is your ingredient: Sugar
What is the quantity of this ingredient: 1
What is the unit of your ingredient: dl
Continue adding ingredients? [y/n]n
>>> print ingredients
[('Flour', 7, 'dl'), ('Butter', 50, 'gr'), ('Sugar', 1, 'dl')]
编辑:将input调用更改为raw_input,因为在python 2.7中,input尝试将输入转换为它认为的输入。因此数字变成整数等等。不一定是个好主意。