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











up vote
0
down vote

favorite












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?










share|improve this question


















  • 4




    Just don't use break? (depending on the rest of the script).
    – Felix Kling
    Mar 7 '12 at 21:20












  • @Felix: He'd still need to wrap his actual code into an else branch, though, which could be prevented by using continue.
    – Niklas B.
    Mar 7 '12 at 21:21

















up vote
0
down vote

favorite












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?










share|improve this question


















  • 4




    Just don't use break? (depending on the rest of the script).
    – Felix Kling
    Mar 7 '12 at 21:20












  • @Felix: He'd still need to wrap his actual code into an else branch, though, which could be prevented by using continue.
    – Niklas B.
    Mar 7 '12 at 21:21















up vote
0
down vote

favorite









up vote
0
down vote

favorite











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?










share|improve this question













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?







python input






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 7 '12 at 21:18









kidosu

138239




138239








  • 4




    Just don't use break? (depending on the rest of the script).
    – Felix Kling
    Mar 7 '12 at 21:20












  • @Felix: He'd still need to wrap his actual code into an else branch, though, which could be prevented by using continue.
    – Niklas B.
    Mar 7 '12 at 21:21
















  • 4




    Just don't use break? (depending on the rest of the script).
    – Felix Kling
    Mar 7 '12 at 21:20












  • @Felix: He'd still need to wrap his actual code into an else branch, though, which could be prevented by using continue.
    – Niklas B.
    Mar 7 '12 at 21:21










4




4




Just don't use break? (depending on the rest of the script).
– Felix Kling
Mar 7 '12 at 21:20






Just don't use break? (depending on the rest of the script).
– Felix Kling
Mar 7 '12 at 21:20














@Felix: He'd still need to wrap his actual code into an else branch, though, which could be prevented by using continue.
– Niklas B.
Mar 7 '12 at 21:21






@Felix: He'd still need to wrap his actual code into an else branch, though, which could be prevented by using continue.
– Niklas B.
Mar 7 '12 at 21:21














2 Answers
2






active

oldest

votes

















up vote
6
down vote













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





share|improve this answer





















  • As Niklas pointed out, it's worth noting that if continue is used, the else condition may be able to be removed as well.
    – Mr. Shickadance
    Mar 7 '12 at 21:23










  • @Sven Marnach what is the use of "PROMPT" in raw_input?? Please clearify it and me also new in python
    – Varun Chhangani
    Apr 15 '14 at 5:25






  • 1




    @VarunChhangani: It's the prompt printed before waiting for user input; see the documentation.
    – Sven Marnach
    Apr 15 '14 at 10:47


















up vote
0
down vote













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)





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f9609213%2fprompt-the-user-to-input-something-else-if-the-first-input-is-invalid%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    6
    down vote













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





    share|improve this answer





















    • As Niklas pointed out, it's worth noting that if continue is used, the else condition may be able to be removed as well.
      – Mr. Shickadance
      Mar 7 '12 at 21:23










    • @Sven Marnach what is the use of "PROMPT" in raw_input?? Please clearify it and me also new in python
      – Varun Chhangani
      Apr 15 '14 at 5:25






    • 1




      @VarunChhangani: It's the prompt printed before waiting for user input; see the documentation.
      – Sven Marnach
      Apr 15 '14 at 10:47















    up vote
    6
    down vote













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





    share|improve this answer





















    • As Niklas pointed out, it's worth noting that if continue is used, the else condition may be able to be removed as well.
      – Mr. Shickadance
      Mar 7 '12 at 21:23










    • @Sven Marnach what is the use of "PROMPT" in raw_input?? Please clearify it and me also new in python
      – Varun Chhangani
      Apr 15 '14 at 5:25






    • 1




      @VarunChhangani: It's the prompt printed before waiting for user input; see the documentation.
      – Sven Marnach
      Apr 15 '14 at 10:47













    up vote
    6
    down vote










    up vote
    6
    down vote









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





    share|improve this answer












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






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Mar 7 '12 at 21:19









    Sven Marnach

    339k75740690




    339k75740690












    • As Niklas pointed out, it's worth noting that if continue is used, the else condition may be able to be removed as well.
      – Mr. Shickadance
      Mar 7 '12 at 21:23










    • @Sven Marnach what is the use of "PROMPT" in raw_input?? Please clearify it and me also new in python
      – Varun Chhangani
      Apr 15 '14 at 5:25






    • 1




      @VarunChhangani: It's the prompt printed before waiting for user input; see the documentation.
      – Sven Marnach
      Apr 15 '14 at 10:47


















    • As Niklas pointed out, it's worth noting that if continue is used, the else condition may be able to be removed as well.
      – Mr. Shickadance
      Mar 7 '12 at 21:23










    • @Sven Marnach what is the use of "PROMPT" in raw_input?? Please clearify it and me also new in python
      – Varun Chhangani
      Apr 15 '14 at 5:25






    • 1




      @VarunChhangani: It's the prompt printed before waiting for user input; see the documentation.
      – Sven Marnach
      Apr 15 '14 at 10:47
















    As Niklas pointed out, it's worth noting that if continue is used, the else condition may be able to be removed as well.
    – Mr. Shickadance
    Mar 7 '12 at 21:23




    As Niklas pointed out, it's worth noting that if continue is used, the else condition may be able to be removed as well.
    – Mr. Shickadance
    Mar 7 '12 at 21:23












    @Sven Marnach what is the use of "PROMPT" in raw_input?? Please clearify it and me also new in python
    – Varun Chhangani
    Apr 15 '14 at 5:25




    @Sven Marnach what is the use of "PROMPT" in raw_input?? Please clearify it and me also new in python
    – Varun Chhangani
    Apr 15 '14 at 5:25




    1




    1




    @VarunChhangani: It's the prompt printed before waiting for user input; see the documentation.
    – Sven Marnach
    Apr 15 '14 at 10:47




    @VarunChhangani: It's the prompt printed before waiting for user input; see the documentation.
    – Sven Marnach
    Apr 15 '14 at 10:47












    up vote
    0
    down vote













    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)





    share|improve this answer



























      up vote
      0
      down vote













      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)





      share|improve this answer

























        up vote
        0
        down vote










        up vote
        0
        down vote









        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)





        share|improve this answer














        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)






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Mar 7 '12 at 22:35

























        answered Mar 7 '12 at 22:10









        Silas Ray

        19.9k53248




        19.9k53248






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f9609213%2fprompt-the-user-to-input-something-else-if-the-first-input-is-invalid%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            這個網誌中的熱門文章

            Academy of Television Arts & Sciences

            L'Équipe

            1995 France bombings