如何防止哨兵值进入循环

时间:2020-07-06 22:32:46

标签: python

我的哨兵值-99一直进入我的while循环,并显示为我的最小输出。如何删除它作为变量或阻止其进入循环?

variable = []
def main():
 userInput = input("What are your numbers? (Follow by -99) ")
 numberInput = [int(x) for x in userInput.split()]
 variable.append(numberInput)
# print(variable)
 count = 0
 while count < len(variable):
   count += 1
   if numberInput == -99:
     break
 larger = max(numberInput)
 smaller = min(userInput)
 print("The highest number is", larger, "and the smallest number is", smaller, ".")


main()

1 个答案:

答案 0 :(得分:0)

def main():
    userInput = input("What are your numbers? (Follow by -99) ")
    numberInput = [int(x) for x in userInput.split()]

    for i in range(len(numberInput)):
        if numberInput[i] == -99:
            del(numberInput[i:]) 
            break
                 
    larger, smaller = max(numberInput), min(numberInput)
    print("The highest number is", larger, "and the smallest number is", smaller, ".")


main()

这里是按原样解决您的问题的方法。将使用无参量进行编辑。问题是您没有从数字输入中删除标记-99。我删除了多余的变量,如果您需要它们来解决问题,那么应该很容易地重新添加它们。简单地转换您的警句:

def main():
    userInput = input("What are your numbers? (Follow by \'none\') ")
    numberInput = list()
    
    for x in userInput.split():
        if x != "none": numberInput.append(int(x))
        else: break
        
    larger, smaller = max(numberInput), min(numberInput)
    print("The highest number is", larger, "and the smallest number is", smaller, ".")


main()

但是我认为这会行得通,但是评论者说,不允许列表理解中断。

numberInput = [int(x) for x in userInput.split() if x != "none" ]不会停止迭代。我不知道为什么在3.8.2中理解的其他方法不起作用,但从理论上讲: numberInput = [int(x) if x != "none" else break for x in userInput.split()]

输出:

What are your numbers? (Follow by 'none') 10 20 30 none 5 40
The highest number is 30 and the smallest number is 10 .