Python如何在达到特定条件后停止添加到列表中

问题描述

我正在做一个项目,用户必须输入该值。如果用户键入大于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 ")

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

解决方法

我认为该程序无法正常运行,因为您做了两个while循环: 第一个while条件是while counter<=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)
,

问题是您的内部while循环无法退出,因为'“”'(退出信号)无法转换为float。相反,它将引发ValueError。 一种可能的解决方案是尝试将输入转换为float,并且将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)