编写一个循环,并将它们存储在一个列表中。 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) 的列表。
查看官方文档中的data structures部分。
演示:
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 尝试将输入转换为它认为的输入。因此数字变成整数等等。不一定是个好主意。