Yes or No answer from user with Validation and restart option?
<p>(py) At the moment, the code below does not validate/output error messages when the user inputs something other than the two choices "y" and "n" because it's in a while loop. </p>

<pre><code>again2=input("Would you like to calculate another GTIN-8 code? Type 'y' for Yes and 'n' for No. ").lower() #**

    while again2 == "y":
        print("\nOK! Thanks for using this GTIN-8 calculator!\n\n")
        restart2()
        break                                                                                                                    #Break ends the while loop

restart2()
</code></pre>

<p>I'm struggling to think of ways that will allow me to respond with an output when they input neither of the choices given. For example:</p>

<pre><code>if again2 != "y" or "n"
   print("Not a valid choice, try again")
   #Here would be a statement that sends the program back to the line labelled with a **
</code></pre>

<p>So, when the user's input is not equal to "y" or "n" the program would return to the initial statement and ask the user to input again. Any ideas that still supports an efficient code with as little lines as possible? Thanks!</p>

<pre><code>def get_choice(prompt="Enter y/n?",choices=["Y","y","n","N"],error="Invalid choice"):
    while True:
        result = input(prompt)
        if result in choices: return result
        print(error)
</code></pre>

<p>is probably a nice generic way to approach this problem</p>

<pre><code>result = get_choice("Enter A,B, or C:",choices=list("ABCabc"),error="Thats not A or B or C")
</code></pre>

<p>you could of coarse make it not case sensitive... or add other types of criteria (e.g. must be an integer between 26 and 88) </p>

python validation loops while-loop restart