python 反复输入_Python-如何让我的程序反复请求输入,但仍然存储其他输入?

写一个循环,并将它们存储在一个列表中。在这里,一个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尝试将输入转换为它认为的输入。因此数字变成整数等等。不一定是个好主意。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值