我想限制用户输入1 - 223,不包括" 3,7,10,12和#34; 当用户输入其中一个号码时,我想打印错误并要求重新提升用户的条目..我在列出排除的号码和重新编码代码时遇到了问题。
这是我停止的地方
for i in range(numRan):
ranNums.append(int(raw_input( "Range %d Number ? (1-223)\n" % (i+1) )))
if i in []:
print "Rang is not allowed!"
答案 0 :(得分:2)
这样做 - 包括在输入无效时重新输入:
allowed_nums = set(range(1,224)) - {3,7,10,12}
for i in range(numRan):
while True:
inpt = int(raw_input("Range %d Number? (1-223)\n" % (i+1)))
if inpt in allowed_nums:
ranNums.append(inpt)
break
print "Range is not allowed!"
所以这基本上起作用的方式是,对于每次迭代或输入,我们创建一个无限循环,只有当输入有效时才会中断,从而进入下一个输入迭代。
答案 1 :(得分:0)
试试这个:
not_allowed = {3,7,10,12}
for i in range(numRan):
while True: # to repeat raw_input if the input is not_allowed
val = int(raw_input( "Range %d Number ? (1-223)\n" % (i+1) )))
if val in not_allowed or val < 1 or val > 223:
print "Rang is not allowed!"
else:
ranNums.append(val)
break
答案 2 :(得分:0)
我通常会为必须重新提示用户的输入编写一个函数
def limited_input(prompt="",include_only=None,not_allowed=None,not_allowed_err="",cast=None,wrongcasterr=""):
if not_allowed is None:
not_allowed = set()
in_ = None
while in_ is None:
in_ = raw_input(prompt)
if cast:
try: in_ = cast(in_)
except ValueError:
print wrongcasterr
in_ = None
continue
if (include_only and in_ not in include_only) or in_ in not_allowed:
print not_allowed_err
in_ = None
return in_
然后你可以像往常一样使用它:
for i in range(numRan):
ranNums.append(limited_input(prompt="Range %d Number ? (1-223)\n" % (i+1),
include_only = range(1,224),
not_allowed = {3,7,10,12},
not_allowed_err = "You cannot use 3,7,10,12"
cast = int
wrongcasterr = "You must enter an integer"))
这个解决方案非常便于携带,我通常将它包含在我的python库中的某个模块或其他模块中。在这个系统上它位于utils.inpututils
但是YMMV
答案 3 :(得分:0)
您可能更容易分离要求函数的函数和创建数字列表层,如下所示:
restrict = [3,7,10,12]
# This function returns an input number with the right
# characteristics.
def strictInput():
v = int(raw_input('Number?'))
if v >0 and v<224 and v not in restrict: return v
print 'Illegal number ..., try again'
return strictInput()
# Now call this function however many times you need ...
inputNumbers = [strictInput() for i in range(numRan)]