Вы можете «улучшить» свою функцию валидатора - вам, вероятно, следует прибегнуть к двум различным функциям, потому что эта функция делает слишком много для одной отдельной функции, но здесь мы идем:
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')