首页 > 解决方案 > 有没有办法简化输入的过滤

问题描述

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

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 循环之前和之后有相同的输入看起来很糟糕)。该功能的原因是我可以在程序的各个部分使用此输入检查功能

标签: python-3.xvalidationinputclosures

解决方案


您可以“增强”您的验证器功能 - 您可能应该使用两个不同的功能,因为这一个功能对于一个单一功能来说太多了,但我们开始吧:

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')

推荐阅读