Python Input Prompt Go Back

后端 未结 2 1875
半阙折子戏
半阙折子戏 2021-01-26 00:35

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.

2条回答
  •  耶瑟儿~
    2021-01-26 00:52

    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.

提交回复
热议问题