python-3.x - 有没有办法简化输入的过滤
问题描述
我正在尝试找到一种更简洁的方法来进行以下输入检查:
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 循环之前和之后有相同的输入看起来很糟糕)。该功能的原因是我可以在程序的各个部分使用此输入检查功能
解决方案
您可以“增强”您的验证器功能 - 您可能应该使用两个不同的功能,因为这一个功能对于一个单一功能来说太多了,但我们开始吧:
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')
推荐阅读
- java - 这是以通用方法调用 Junit 断言的好方法吗?
- database - 如何从一个字段是其他字段组合的弹性搜索中获取数据
- javascript - 反应中的样式设置错误为未定义的“宽度”
- android - 如何对运行 Android 11 (SDK 30) 的应用程序崩溃进行故障排除
- wordpress - Elementor 说 - “抱歉,在您的页面中找不到内容区域。”同时使用自定义简码
- java - 一个接一个的放置JPanel就是隐藏之前附加的JPanel
- c# - 为什么 Audit.NET 为 AuditContext 获取本地 DbContext 以记录数据
- java - Java中的构造函数链接和超级关键字
- presto - EMR Presto LDAPS:未加载身份验证器
- react-native - 流式传输 RTMP 与覆盖,反应原生