Python菜单程序:输入非有效选项时如何实现无操作?
Got it, let's sort out this menu problem for you. Your current code has two main issues:
- The recursive call to
mainMenu()refreshes the screen every single time—even when someone enters an invalid option, which is exactly what you don't want. - You're using two separate
ifstatements instead ofif-elif-else, so theelseblock actually triggers when you select option 1 (since it doesn't match the secondifcondition for '2'). That's a hidden logic bug!
Here's how to fix it so invalid inputs do absolutely nothing—no screen refresh, no program exit, just wait for the next command:
We'll ditch the recursion and use a while True loop instead. This lets us keep the menu visible unless a valid option is processed (and even then, you can choose whether to refresh it). Here's the revised code:
import os def mainMenu(): # Draw the menu once at the start os.system("clear") print("menu") print("1 - option 1") print("2 - option 2") # Keep listening for input forever while True: selection = raw_input("Enter your choice: ") # Use `input()` instead if you're on Python 3 if selection == '1': # Run your super-interesting code here print("Executing option 1...") # Optional: Refresh the menu after processing (remove if you don't want this) os.system("clear") print("menu") print("1 - option 1") print("2 - option 2") elif selection == '2': # Run your Kim Kardashian/Eskimo/polar bear code here print("Executing option 2...") # Optional: Refresh menu after processing os.system("clear") print("menu") print("1 - option 1") print("2 - option 2") else: # Do literally nothing—just loop back to wait for next input # If you want to give a tiny feedback (optional), uncomment this line: # print("Invalid option. Try again.") pass mainMenu()
Key improvements:
- No more recursion: The
while Trueloop keeps the program running without reloading the menu on every input. - Fixed conditional logic: Using
if-elif-elseensures theelseonly triggers when the input isn't '1' or '2'—not when you select a valid option. - Non-intrusive invalid handling: The
passin theelseblock means absolutely nothing happens when someone enters a bad option. The menu stays up, the program keeps running, and it just waits for the next input.
If you don't want to refresh the menu even after valid options (maybe you want to show the result of the action next to the menu), just remove the os.system("clear") and menu print lines inside the if and elif blocks. The menu will stay visible the whole time, and only the action output will appear below it.
内容的提问来源于stack exchange,提问作者szafran

