如何在Python开发的USSD应用中实现返回主菜单功能
Hey there! I see you've got a solid start on your multi-operator USSD app, but the back button (selecting 0 in submenus) isn't working as expected. That's because your current function exits after returning a value—USSD apps need to maintain a session loop to handle navigation between menus. Let's refactor your code to fix this, plus clean up the repeated logic for each operator!
Core Improvements We'll Make
- Use loops to maintain the session: Keep the app running in a loop until the user chooses to exit, instead of returning immediately.
- Encapsulate repeated code: Since all three operators use the same menu structure, we'll create reusable functions to avoid redundant code.
- Handle back navigation: When the user selects 0 in a submenu, we'll signal the main loop to redisplay the main menu instead of exiting.
Refactored Code
# Global menu definitions menu_option = ["1. buy data", "2. top up", "3. exit"] buy_data = ["1. N100 for 100mb", "2. N200 for 200mb", "0.back"] top_up = ["1. self", "2. third party", "0.back"] def display_menu(menu_title, menu_items): """Reusable function to display menu options cleanly""" print(f"\n{menu_title}") for item in menu_items: print(f"- {item}") def handle_buy_data(): """Handle buy data submenu logic with back support""" while True: display_menu("Choose a data plan:", buy_data) try: buy_data_plan = int(input("Enter your choice: ")) if buy_data_plan == 1: return f"You have selected\n\n{buy_data[0]}" elif buy_data_plan == 2: return f"You have selected\n\n{buy_data[1]}" elif buy_data_plan == 0: return "back_to_main" # Signal to return to main menu else: print("Wrong input! Please enter a valid number.") except ValueError: print("Invalid input! Please enter a numeric value.") def handle_top_up(): """Handle top up submenu logic with back support""" while True: display_menu("Select a top up plan:", top_up) try: top_up_plan = int(input("Enter your choice: ")) if top_up_plan == 1: self_num = input("Enter your number: ") return f"Successfully credited airtime on {self_num}" elif top_up_plan == 2: third_party_num = input("Enter third party number: ") return f"Successfully credited airtime on {third_party_num}" elif top_up_plan == 0: return "back_to_main" # Signal to return to main menu else: print("Wrong input! Please enter a valid number.") except ValueError: print("Invalid input! Please enter a numeric value.") def ussd_app(): """Main USSD app session handler""" code = input("Enter a USSD code: ") # Map USSD codes to operator welcome messages operator_config = { "*131#": "Welcome to MTN!", "#124#": "Welcome to GLOBACOM!", "#121#": "Welcome to AIRTEL!" } if code not in operator_config: print("Wrong USSD code! Please try again.") return print(f"\n{operator_config[code]}") # Main menu loop to maintain session while True: display_menu("Please select a package:", menu_option) try: menu_choice = int(input("Enter your choice: ")) if menu_choice == 1: result = handle_buy_data() if result != "back_to_main": print(f"\n{result}") break # Remove this if you want to stay in the session after selection elif menu_choice == 2: result = handle_top_up() if result != "back_to_main": print(f"\n{result}") break # Remove this if you want to stay in the session after selection elif menu_choice == 3: print("\nYou have exited the USSD interface!") break else: print("Wrong input! Please enter a valid number.") except ValueError: print("Invalid input! Please enter a numeric value.") # Launch the USSD app ussd_app()
Key Changes Explained
- Reusable Functions:
display_menu,handle_buy_data, andhandle_top_upeliminate duplicate code across operators, making your app easier to update later. - Back Navigation: When the user selects 0 in a submenu, we return the string
"back_to_main". The main loop detects this signal and redraws the main menu instead of exiting. - Input Validation: Added
try/exceptblocks to handle non-numeric inputs gracefully, so the app doesn't crash if the user enters text instead of a number. - Operator Abstraction: Used a dictionary to map USSD codes to welcome messages, replacing three separate
ifblocks with a clean lookup.
Optional Adjustment
If you want to keep the user in the session after they complete an action (like buying data), just remove the break statements after printing the result. This way, they'll be taken back to the main menu automatically instead of exiting the app.
内容的提问来源于stack exchange,提问作者Ibikunle The Creator
相关产品推荐
相关产品推荐

