为由字符串和整数组成的元素创建循环

时间:2015-09-24 02:15:58

标签: python python-2.7

我正在制作一个程序而无法完成第一部分。

while True:
print "1. Add an item."
print "2. Find an item."
print "3. Print the message board."
print "4. Quit."
choice = input("Enter your selection: ")
if choice == 1:
    item = raw_input("Enter the item type-b,m,d,t,c:")
    cost = raw_input("Enter the item cost:")
    elts = []
    elts.append([item,cost])
if choice == 4:
    print elts
    break

我现在的问题是我需要弄清楚如何

2 个答案:

答案 0 :(得分:0)

第一项任务:使流程循环。由于退出的输入为4,因此只需将所有代码放在while choice == 4中断的while循环中。

while True:
    print("1. Add an item.")
    print("2. Find an item.")
    print("3. Print the message board.")
    print("4. Quit.")
    choice = input("Enter your selection: ")
    if choice == 1:
        item = input("Enter the item type-b,m,d,t,c: ")
        price = input("Enter the item cost: ")
    if choice == 4:
        break

第二项任务是存储用户输入的所有项目和价格。我建议使用字典。首先,在while循环之外初始化一个字典:

d = {}
while True:
    ...

然后,在输入后,将item添加到字典中,并将price作为其值。

item = input("Enter the item type-b,m,d,t,c: ")
price = input("Enter the item cost: ")
d[item] = price

答案 1 :(得分:0)

尝试将选择变量和其他变量放在while循环中以保持重复,并在获得所需输入后,将项目和价格变量一起添加?不确定那是不是你正在寻找的东西,但它尽可能接近我希望它有所帮助