【问题标题】:Creating a loop for a elements made of strings and integers为由字符串和整数组成的元素创建循环
【发布时间】:2015-09-24 02:15:57
【问题描述】:

我正在编写一个程序,但无法完成第一部分。

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

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

【问题讨论】:

  • 你试过什么?如果您发布代码,以便我们知道您实际上尝试自己解决此问题,那么有人会更有可能帮助您。
  • 听起来好像有人只是试一试,而且是新手。我讨厌人们对不熟悉协议的问题投反对票。弗兰克 - 如果您发布您的代码并告诉我们有什么问题,我们可以提供帮助。
  • 他的代码不起作用,因为choice 将是一个字符串,而'1' != 1
  • @IanAuld 实际上这不是真的。在 Python 2.x 中,input() 等价于eval(raw_input()),这意味着如果用户输入1,它将具有int 的类型。 raw_input()(与 Python 3 中的 input() 具有相同的行为)总是会返回 str,但 input() 会尝试将输入转换为正确的数据类型。一般来说,一个人应该只使用raw_input()。例如:In [1]: type(input()) 1 Out[1]: int In [2]: type(raw_input()) 1 Out[2]: str

标签: python python-2.7


【解决方案1】:

尝试将选择变量和其他变量放在一个while循环中以使其重复,并在获得所需输入后,将项目和价格变量加在一起?不确定这是否是您真正想要的,但它尽可能接近希望它有所帮助

【讨论】:

    【解决方案2】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-31
      • 1970-01-01
      • 2019-01-26
      • 1970-01-01
      相关资源
      最近更新 更多