使用python shell过滤范围之外的数据

时间:2018-01-01 20:39:56

标签: python python-3.x user-input

我正在尝试编写一个程序,让用户输入一个数字列表并告诉他们最大和最小数字。程序应该让用户选择允许的最小值和最大值,并且不应该让用户输入一些超出这些边界的列表。我已经设法完成了第一次,但我不知道如何过滤范围之外的数据。非常感谢帮助。

print ("Input done when finished")
print ("Input thresholds")

maximumnum = int(input("Input maximum number: "))
minimumnum = int(input("Input minimum number: "))


minimum = None
maximum = None

while True:
    inp =input("Enter a number: ")
    if inp == "done": 
    break

    try:
        num = float(inp)
    except:
        print ("Invalid input")
        continue                            

    if minimum is None or num < minimum:
        minimum = num

    if maximum is None or num > maximum:
        maximum = num

print ("Maximum:", maximum)
print ("Minimum:", minimum)

1 个答案:

答案 0 :(得分:1)

您需要在try / except块下添加此附加检查:

# To check your number is not greater than maximum allowed value
if num > maximumnum:
    print('Number greater the maximum allowed range')
    break

# To check your number is not smaller than maximum allowed value
if num < minimumnum:
    print('Number smaller the maximum allowed range')
    break

因此,您的完整代码将变为:

print ("Input done when finished")
print ("Input thresholds")

maximumnum = int(input("Input maximum number: "))
minimumnum = int(input("Input minimum number: "))


minimum = None
maximum = None

while True:
    inp =input("Enter a number: ")
    if inp == "done": 
        break

    try:
        num = float(inp)
    except:
        print ("Invalid input")
        continue  

    ## ---- Additional Check ---- ##
    if num > maximumnum:
        print('Number greater the maximum allowed range')
        break

    if num < minimumnum:
        print('Number smaller the maximum allowed range')
        break        
    ## -------------------------- ##                  

    if minimum is None or num < minimum:
        minimum = num

    if maximum is None or num > maximum:
        maximum = num

print ("Maximum:", maximum)
print ("Minimum:", minimum)