Есть ли способ упростить фильтрацию входов - PullRequest
0 голосов
/ 01 ноября 2018

Я пытаюсь найти более удобный способ выполнить следующую проверку ввода:

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 голосов
/ 01 ноября 2018

Вы можете «улучшить» свою функцию валидатора - вам, вероятно, следует прибегнуть к двум различным функциям, потому что эта функция делает слишком много для одной отдельной функции, но здесь мы идем:

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