【问题标题】:Python how to stop adding into list after hitting certain criteriaPython如何在达到某些条件后停止添加到列表中
【发布时间】:2020-08-13 13:40:44
【问题描述】:

我正在做一个用户必须输入值的项目。如果用户键入超过 300 的值 3 次,则循环应该结束。如果用户键入的值小于 300,则应提示警告消息。另一个标准是,如果用户不满足上述条件,我需要允许用户退出循环。目前,我尝试使用列表来完成,但我的代码似乎没有计算输入的数量。

list1 = list()
counter = 1 
while counter <= 3: 
    ask = float(input("Please enter each of the value: ")) 
    while ask != "":
        list1.append(str(ask))
        ask = float(input("Please enter each of the value: "))
        if ask >= 50:
            counter += 1 
        else:
            print("Value must be more than 300. If you do not meet the criteria, please press 'enter'. ")
print(list1)

以下代码是我的原始代码,没有考虑最小输入值。

counter = 1 
while counter <= 3:
    ask = float(input("Please enter each of the value: ")) 
    if ask >= 50:
        counter += 1 
    else:
        print("Value must be more than 300 ")

如果有人能帮助我,我将不胜感激。

【问题讨论】:

    标签: python python-3.x loops if-statement while-loop


    【解决方案1】:

    问题是您的内部 while 循环无法退出,因为 ' "" '(您的退出信号)无法转换为浮点数。相反,它会引发 ValueError。 一种可能的解决方案是尝试将输入转换为浮点数,但 ValueError 除外。它可能看起来像这样。

    list1 = list()
    counter = 1
    while counter <= 3:
        try:
           ask = float(input("Please enter each of the value: "))
        except ValueError:
           break
        list1.append(str(ask))
        if ask >= 50:
            counter += 1 
        else:
            print("Value must be more than 300. If you do not meet the criteria, please press 'enter'. ")
    
    print(list1)
    

    【讨论】:

      【解决方案2】:

      我认为该程序无法按您的意愿运行,因为您创建了两个 while 循环: 第一个while的条件是while counter&lt;=3,好的,但是你又做了一个while,条件是ask !="",所以程序将在第二个while循环中运行,直到条件不再为真并且第一个while没有“看到”计数器的变化。

      顺便说一句,我认为你可以只使用一个 while 循环(第一个),然后编写一个 if 条件来验证值(>300)。

      当您尝试将字符串元素转换为浮点类型时,如果无法将值转换为该类型,则会引发错误,您可以使用 try-except 块。

      while counter < 3:
            try:
                 ask = float(input("xxxxx")
                 if ask >= 50:
                     counter += 1
                 else:
                     print("xxxxx")
            except ValueError:
                 break
      print(list1)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-08-12
        • 2018-04-05
        • 2019-10-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-12
        相关资源
        最近更新 更多