I have a script which has multiple raw_input statements. I would like to add the ability to enter \'undo\' and allow the user to go back and re-enter the last raw_input value.
The first way that comes to mind is to separate what you do with each input into a function. That way you can build a list of these functions and progress through them one by one. This means that if the user enters the undo input, you can take one step back and go to the previous function.
def function1(user_input):
# do something
def function2(user_input):
# do something
def function3(user_input):
# do something
processing_functions = [function1, function2, function3]
progress = 0
The above is the set up. Each function can take the user's input and do whatever it needs to with it. In case you're not familiar, lists take references to functions too. And you can call a function from a list just by accessing the index and then using the parentheses, eg. processing_functions[0](user_input)
.
So now here's how we'd do the actual loop:
while progress < len(processing_functions):
user_input = raw_input("Enter input please.")
if user_input == "UNDO":
progress -= 1
print("Returning to previous input.")
else:
print("Processing " + user_input)
processing_functions[progress](user_input)
progress += 1
print("Processing complete.")
You keep running the loop while you have functions left to do (progress is less than the number of functions), and keep calling each function. Except, if the undo command is used, progress is dropped by one and you run the loop again, with the previous function now.
looks like you coded in a wrong way, an input raw cannot be your point ... maybe you should create an unique raw input and keep the entry into an array
ok....now u post a code example i got it...my suggestion:
import sys
def do(prompt, step):
if 'u' in prompt:
step = step-1
else:
step = step+1
if step>1:
print('Please enter x for x \nPlease enter y for y \nPlease enter c to cancel \nPlease enter u to go back to previous question: ')
else:
print('Please enter x for x \nPlease enter y for y \nPlease enter c to cancel: ')
return step
step = 0
prompt = ""
while prompt != 'c':
step = do(prompt, step)
prompt = raw_input().lower()