简体   繁体   中英

Backtracking in a while loop (python 3.x)

I'm reasonably new to Python. I wanted to know if I could use an input and ask a question like 'are you sure?', and if the answer is no to go back to the original input. I've got this so far:

variable = input("Make a choice between a, b, c or d. ")
while variable not in ("a","b","c","d"):
    variable = input("Make a correct choice. ")

if variable == "a":
    do things
if variable == "b":
    do other things
etc etc

I want to ask, after they have typed in their choice, are you sure about your choice? If they say yes, that's fine, carry on, but if they say 'no' I want to be able to go to the same input without typing the whole thing out again. Is there any way to do that?

You could embed the bit that you want to repeat in a while True block that you break out of? For example:

while True
    answer = input("What is the correct answer, a, b, or c? ")
    check = input("Are you sure (y/n)? ")
    if check=="y" or check=="Y":
        break

Take the code you already have and wrap it in another while loop:

# loop forever until they confirm their choice
while True:
    variable = input("Make a choice between a, b, c or d. ")
    while variable not in ("a","b","c","d"):
        variable = input("Make a correct choice. ")
    confirm = input("You entered %s.  Is this correct?" % variable)
    if confirm == "yes":
        break

Something like this will work (though it's not the cleanest thing right now).

def prompt_for_something():
   variable = input("Make a choice between a, b, c or d. ")
   while variable not in ("a","b","c","d"):
       variable = input("Make a correct choice. ")

   confirm = input("Are you sure?")

   if confirm == "No": return False
   return variable

option = prompt_for_something()
while option == False:
   option = prompt_for_something()

if option == "a":
   do something
ok=False
while not OK:
    variable = input("Make a choice between a, b, c or d. ")
    while variable not in ("a","b","c","d"):
        variable = input("Make a correct choice. ")
    ishesure=input("You chose {},  Are you sure?  (Y or N)".format(variable))
    if ishesure=="Y":
        ok=True

Should work. You surround everything by a while loop that will loop until the customer enters "Y" to your second question, that is asked once he entered a valid value for variable

It is not easy to have editable console output. If it is just for you, you can press the 'up' arrow key to go back to your last input, but if you want to embed it into the code it may be easier to use a proper GUI (ie tkinter) than what you are doing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM