Prompt the user to input something else if the fir

2019-01-12 13:15发布

问题:

I'm very new to Python, so forgive my newbish question. I have the following code:

[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]

If I wanted to, instead of breaking the loop and quitting the program, send the user back to the original prompt until they input valid data, what would I write instead of break?

回答1:

To go on with the next loop iteration, you can use the continue statement.

I'd usually factor out the input to a dedicated function:

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


回答2:

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()

Slight alternative:

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()

Or, if you wanted to break it out in to a function (this function is overkill for this use, but an entire function for a special case is suboptimal 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

This method lets you define your validator. You would call it thusly:

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)


标签: python input