如何为Python反转消息程序添加重复运行或退出的选择功能?
First, let's tweak your existing code to add the "continue or exit" prompt after each message reversal. Here's a revised version that works smoothly:
print("\nHi, welcome to my program that will reverse your message") # Loop indefinitely until the user chooses to exit while True: var_string = input("\nSo tell me, what would you like said backwards: ") print("So your message in reverse is:", var_string[::-1]) # Ask user if they want to keep going user_choice = input("\nWant to reverse another message? (y/n): ").strip().lower() # Exit the loop if user doesn't choose 'y' if user_choice != 'y': break print("\nThanks for using the program! Have a great day!")
This replaces your original start variable with a while True loop (which runs forever unless we explicitly break out of it). Stripping extra spaces and converting input to lowercase makes the program robust against typos like "Y" or " N ".
When building programs that let users decide to rerun or exit, here are the most reliable approaches:
1. Use while True with break (Simplest)
This is the approach we used above. You loop indefinitely, then check for an exit condition to break out of the loop. It’s clean and easy to read for straightforward use cases.
2. Use a Flag Variable
If you prefer a more explicit loop condition, a boolean flag works well:
continue_running = True while continue_running: # Your core program logic here message = input("Enter a message to reverse: ") print("Reversed:", message[::-1]) # Update flag based on user choice choice = input("Continue? (y/n): ").strip().lower() if choice == 'n': continue_running = False
3. Add Input Validation (For Robustness)
Users often enter unexpected inputs, so adding a check to enforce valid responses prevents odd behavior:
while True: # Core program logic message = input("Enter a message to reverse: ") print("Reversed:", message[::-1]) # Keep asking until valid input is provided while True: choice = input("Continue? (y/n): ").strip().lower() if choice in ['y', 'n']: break print("Invalid input—please enter 'y' or 'n'.") if choice == 'n': break
This nested loop ensures the user can’t proceed until they enter a valid response.
内容的提问来源于stack exchange,提问作者Marco Ball-Albarran

