Prompt the user to input something else if the first input is invalid

后端 未结 2 1037
孤城傲影
孤城傲影 2020-11-30 15:42

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         


        
相关标签:
2条回答
  • 2020-11-30 16:18
    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)
    
    0 讨论(0)
  • 2020-11-30 16:39

    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.")
    
    0 讨论(0)
提交回复
热议问题