Python - 如何让程序重复询问输入但仍然保存其他输入?

0 投票
3 回答
10520 浏览
提问于 2025-04-18 01:04

基本上,我的程序需要能够存储食谱。我需要让用户输入一种食材,以及它的数量和单位。抱歉如果这听起来有点模糊,但我该如何编程,让用户可以输入多个食材,直到他们输入完所需的食材数量呢?非常感谢。

#Ask the user to input ingredient name, quantity and measurement

ingredient = input("Name is your ingredient: ")
ingredientquantity = int(input("What is the quantity of this ingredient: "))
ingredientunit = input("What is the unit of your ingredient: ")

^^^ 这是我目前写的代码,但我该如何让这个过程重复进行,并且仍然能够保存之前输入的内容呢?

3 个回答

0

你可以试试下面这个:

data = []

i=0
max_cycles = 10
while i < max_cycles:

    ingredient = input("Name is your ingredient: ")
    ingredientquantity = int(input("What is the quantity of this ingredient: "))
    ingredientunit = input("What is the unit of your ingredient: ")
    data.append((ingredient, ingredientquantity, ingredientunit))

    print(data)

    i += 1

这个代码会循环执行10次(也就是max_cycles的值),然后停止,并把所有的数据以元组的形式存储在data列表里。

1

在编程中,有时候我们需要处理一些数据,比如从一个地方获取数据,然后在程序里使用它。这就像你从冰箱里拿出食材,然后用它们做饭一样。

有些时候,数据的格式可能会让我们感到困惑。比如,数据可能是以字符串的形式存在,这就像是把食材放在一个袋子里,而我们需要把它们拿出来,才能用来做菜。

为了让程序能够理解这些数据,我们需要将它们转换成合适的格式。这就像是把食材切成小块,方便我们烹饪。

在处理数据时,我们还需要注意一些细节,比如数据的类型、结构等等。这就像在做饭时,我们需要知道哪些食材可以一起搭配,哪些不能。

总之,处理数据就像做饭一样,需要耐心和技巧,才能做出美味的“菜肴”。

def validated_input(prompt,input_type=str):
    while True:
       try:
            return input_type(raw_input(prompt))
       except:
            print "Error Invalid Input, Try Again"

def get_ingredient():
    return validated_input("Ingredient Name:",str),validated_input("Qty:",int),validated_input("Units:",str)


ingredients = [get_ingredient() for _ in range(validated_input("Enter Number Of Ingredients:",int))]
4

写一个循环,把你需要的东西存到一个列表里。这里用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),你就会得到一个包含三元组的列表,格式是(成分名称, 成分数量, 成分单位)

可以看看官方文档中的数据结构部分。

示例:

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会试图把输入转换成它认为的类型。所以数字会变成整数等等。这并不一定是个好主意。

撰写回答