Search code examples
pythonpython-3.xuser-input

Filtering Data outside of a range using python shell


I'm attempting to write a program that lets the user input a list of numbers and tell them maximum and minimum numbers. The program should let the user choose the allowable minimum and maximum values, and should not let the user input something to the list that is outside of these bounds. I've managed to get the first bit done but I have no idea how to filter data outside of a range. Help would be greatly appreciated.

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)

Solution

  • You need to add this additional check below the try/except block:

    # 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
    

    Hence, your complete code will become:

    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)