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



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

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)
您需要在

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)

相关内容

  • 没有找到相关文章

最新更新