有没有一种方法可以简化输入过滤

时间:2018-11-01 19:25:16

标签: python-3.x validation input closures

我正在尝试找到一种更整洁的方法来进行以下输入检查:

def intInputCheck():
    while True:
        try:
            INPUT = int(input("INPUT -> "))
            return INPUT
        except ValueError:
            print("Please only input integers")

def createGroup():

    possibleSupervisors = ["USER1","USER2"] #etc

    print("Possible supervisors:\n{}".format(possibleSupervisors))
    for i in range(0, len(possibleSupervisors)):
        print(i, ":", possibleSupervisors[i][0])
    """
    supervisor = intInputCheck
    while supervisor() not in range(0, len(possibleSupervisors)):
        print("Please only input numbers in the range provided")
    """
    #The above kinda works, but i cant then use the variable "supervisor"
    """

    supervisor = intInputCheck()
    while supervisor not in range(0, len(possibleSupervisors)):
        supervisor = intInputCheck()
        print("Please only enter integers in the given range")
    """
    """
       The above works, however I end up giving out two print statements if 
       the user doesnt input an integer which I don't want, I want it to 
       only output the print statement if that specific error occurs, in 
       this, If a str is entered, the func will output "only enter ints" and 
       then the while will output "only ints in given range" which is a pain
    """

我还试图查看闭包是否对简化这段代码有用,我这样做的原因是使我的代码更整洁(我认为在while循环之前和之后使用相同的输入看起来很糟糕)。 之所以使用该功能,是因为我可以在程序的各个部分中使用此输入检查功能

1 个答案:

答案 0 :(得分:1)

您可以“增强”验证器功能-您可能应该诉诸两种不同的功能,因为对于一个功能而言,这一功能的作用太大,但是我们开始:

def intInputCheck(text,error,options=[]):
    """Prints 'text' and optional a list of (1-based) 'options' and loops
    till a valid integer is given. If 'options' are given, the integer must
    be inside 1..len(options).

    The return is either an integer or a tuple of the 1-based list index and the 
    corresponding value from the list."""
    msg = [text]
    test = None
    if options:
        test = range(1,len(options)+1)
        for num,t in enumerate(options,1):
            msg.append("{:>2} : {}".format(num,t))
        msg.append("Choice -> ")

    while True:
        try:
            INPUT = int(input('\n'.join(msg)))
            if test is None:
                return INPUT
            elif INPUT in test:
                return (INPUT,options[INPUT-1])
            else:
                raise ValueError
        except ValueError:
            print(error)

k = intInputCheck("INPUT -> ","Please only input integers")

sup = intInputCheck("Possible supervisiors:", 
                    "Choose one from the list, use the number!",
                    ["A","B","X"])     

print(k)
print(sup)

输出:

# intInputCheck("INPUT -> ","Please only input integers")
INPUT -> a
Please only input integers
INPUT -> b
Please only input integers
INPUT -> 99

# intInputCheck("Possible supervisiors:", "Choose one from the list, use the number!", 
#               ["A","B","X"])  
Possible supervisiors:
 1 : A
 2 : B
 3 : X
Choice -> 8
Choose one from the list, use the number!
Possible supervisiors:
 1 : A
 2 : B
 3 : X
Choice -> 6
Choose one from the list, use the number!
Possible supervisiors:
 1 : A
 2 : B
 3 : X
Choice -> 2

结果:

# k
99

# sup
(2, 'B')
相关问题