【问题标题】:Python 3: Append integers on a list with while True loopPython 3:使用 while True 循环在列表中追加整数
【发布时间】:2020-04-20 15:05:23
【问题描述】:

我正在尝试做以下练习:

任务 4

创建一个空列表purchase_amounts 使用用户输入的项目价格填充列表继续添加到列表中,直到输入“完成”

可以使用 while True: with break

打印购买金额

这是我目前的代码:

#[ ] complete the Register Input task above
purchase_amounts=[]
purchase_amounts.append(input("Enter the prices: "))
while True:
    if input("Enter the prices: ") != "done":
        purchase_amounts.append(input("Enter the prices: "))
    else:
        break
print(purchase_amounts)

但它给了我这样一个非常奇怪的输出:

输入价格:2222222

输入价格:1

输入价格:2

输入价格:3

输入价格:完成

输入价格:完成

['2222222', '2', '完成']

有人知道为什么它会覆盖第二个、第四个和第五个输入并且它没有将值添加到列表中吗?非常感谢!

【问题讨论】:

  • 你需要稍微重构一下。 input() 返回用户输入的字符串。在 while 循环中,如果值不等于“done”,则丢弃该值,并再次提示用户。因此,将值存储在某处,然后与该(存储的)值进行比较。
  • 这是因为,你调用了两次输入函数。将输入存储在局部变量中并比较局部变量。

标签: python python-3.x


【解决方案1】:

您输入的次数过多。

您应该只通过调用input() 在每个循环中输入一次,然后添加到列表中。您可能还想将输入转换为带有float 的数字。

purchase_amounts=[]
while True:
    user_input = input("Enter the prices: ")
    if user_input != "done":
        purchase_amounts.append(float(user_input))
    else:
        break
print(purchase_amounts)

输出:

Enter the prices: 12
Enter the prices: 13
Enter the prices: done
[12, 13]

【讨论】:

    【解决方案2】:

    您有 2 个 input(),但实际上只使用了一个。检查 cmets:

    while True:
        if input("Enter the prices: ") != "done":                   #Here you only compare the input with "done" but you don't do anything with it
            purchase_amounts.append(input("Enter the prices: "))    #here you ask for a second input
    

    您只能要求输入一次并将其保存在变量中:

    while True:
        value_input = input("Enter the prices: ")
        if value_input != "done":                   
            purchase_amounts.append(value_input)    
        else:
            break
    

    PS:你可能想把字符串转换成int,不是吗?

    【讨论】:

      【解决方案3】:
      purchase_amounts=[]
      while True:
          a=input("Enter price of Items :")
          if a=='Done':
              break
          else:
              purchase_amounts.append(a)
      
      print(purchase_amounts)
      

      【讨论】:

        【解决方案4】:

        尝试与 IF 分开使用测试用例。

        请注意,!= 的 python 方式是not (test case)

        purchase_amounts=[]
        # purchase_amounts.append(input("Enter the prices: ")) <- this can be sacked
        while True:
            test_case = input("Enter the prices: ")
            if not test_case == "done":
                purchase_amounts.append(input("Enter the prices: "))
            else:
                break
        print(purchase_amounts)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-11-23
          • 2020-07-03
          • 2013-10-30
          • 2014-05-09
          • 2017-07-14
          • 2022-06-10
          相关资源
          最近更新 更多