Ask the user if they want to repeat the same task again

后端 未结 2 458
渐次进展
渐次进展 2020-11-29 12:57

If the user gets to the end of the program I want them to be prompted with a question asking if they wants to try again. If they answer yes I want to rerun the program.

相关标签:
2条回答
  • 2020-11-29 13:24

    You can enclose your entire program in another while loop that asks the user if they want to try again.

    while True:
      # your entire program goes here
    
      try_again = int(input("Press 1 to try again, 0 to exit. "))
      if try_again == 0:
          break # break out of the outer while loop
    
    0 讨论(0)
  • 2020-11-29 13:27

    This is an incremental improvement on the accepted answer:

    Used as is, any invalid input from the user (such as an empty str, or the letter "g" or some such) will cause an exception at the point where the int() function is called.

    A simple solution to such a problem is to use a try/except- try to perform a task/ code and if it works- great, but otherwise (except here is like an else:) do this other thing.

    Of the three approaches one might try, I think the first one below is the easiest and will not crash your program.

    Option 1: Just use the string value entered with one option to go again

    while True:
        # your entire program goes here
        
        try_again = input("Press 1 to try again, any other key to exit. ")
        if try_again != "1":
            break # break out of the outer while loop
    

    Option 2: if using int(), safeguard against bad user input

    while True:
        # your entire program goes here
    
        try_again = input("Press 1 to try again, 0 to exit. ")
        try:
            try_again = int(try_again)  # non-numeric input from user could otherwise crash at this point
            if try_again == 0:
                break # break out of this while loop
        except:
            print("Non number entered")
        
    

    Option 3: Loop until the user enters one of two valid options

    while True:
        # your entire program goes here
        
        try_again = ""
        # Loop until users opts to go again or quit
        while (try_again != "1") or (try_again != "0"):
            try_again = input("Press 1 to try again, 0 to exit. ")
            if try_again in ["1", "0"]:
                continue  # a valid entry found
            else:
                print("Invalid input- Press 1 to try again, 0 to exit.")
        # at this point, try_again must be "0" or "1"
        if try_again == "0":
            break
    
    0 讨论(0)
提交回复
热议问题