如果第一个输入无效,则提示用户输入其他内容

时间:2012-03-07 21:18:10

标签: python input

我是Python的新手,请原谅我的新问题。我有以下代码:

[a while loop starts]

print 'Input the first data as 10 characters from a-f'

input1 = raw_input()
if not re.match("^[a-f]*$", input1):
    print "The only valid inputs are 10-character strings containing letters a-f"
    break
else:
[the rest of the script]

如果我想,而不是打破循环并退出程序,请将用户返回到原始提示,直到他们输入有效数据,我会写什么而不是中断?

2 个答案:

答案 0 :(得分:6)

继续下一个循环迭代,您可以使用continue statement

我通常将输入分解为专用函数:

def get_input(prompt):
    while True:
        s = raw_input(prompt)
        if len(s) == 10 and set(s).issubset("abcdef"):
            return s
        print("The only valid inputs are 10-character "
              "strings containing letters a-f.")

答案 1 :(得分:0)

print "Input initial data.  Must be 10 characters, each being a-f."
input = raw_input()
while len(input) != 10 or not set(input).issubset('abcdef'):
    print("Must enter 10 characters, each being a-f."
    input = raw_input()

轻微替代方案:

input = ''
while len(input) != 10 or not set(input).issubset('abcdef'):
    print("Input initial data.  Must enter 10 characters, each being a-f."
    input = raw_input()

或者,如果你想把它分解成一个函数(这个函数对于这个用法来说太过分了,但是特殊情况的整个函数是次优的imo):

def prompt_for_input(prompt, validate_input=None, reprompt_on_fail=False, max_reprompts=0):
    passed = False
    reprompt_count = 0
    while not (passed):
        print prompt
        input = raw_input()
        if reprompt_on_fail:
            if max_reprompts == 0 or max_reprompts <= reprompt_count:
                passed = validate_input(input)
            else:
                passed = True
        else:
            passed = True
        reprompt_count += 1
   return input

此方法允许您定义验证器。你会这么称呼它:

def validator(input):
    return len(input) == 10 and set(input).subset('abcdef')

input_data = prompt_for_input('Please input initial data.  Must enter 10 characters, each being a-f.', validator, True)