Python simple menu

Python Simple Menu

In Python, you can create a simple menu by using loops and conditional statements. Here’s an example:

<python>
menu_choices = ["1. Option A", "2. Option B", "3. Option C", "4. Exit"]

def print_menu():
    for choice in menu_choices:
        print(choice)

def handle_option(option):
    if option == "1":
        print("You selected Option A.")
    elif option == "2":
        print("You selected Option B.")
    elif option == "3":
        print("You selected Option C.")
    elif option == "4":
        print("Exiting the menu...")
        return False
    else:
        print("Invalid option.")

def main_menu():
    while True:
        print_menu()
        option = input("Select an option: ")
        if not handle_option(option):
            break

main_menu()
</python>

In this example, we first define a list of menu choices. The print_menu() function simply loops over the menu choices and prints them to the console. The handle_option() function handles the user’s choice. If the option is valid, it shows a corresponding message. If the option is “4”, it returns False to exit the menu. If the option is invalid, it prints an error message.

The main_menu() function is an infinite loop that calls print_menu(), prompts the user for an option, and calls handle_option() based on the user’s input. If the handle_option() function returns False (meaning the user selected the exit option), the loop breaks and the menu ends.

This is a basic example, but you can expand on it by adding additional menu options and functionality based on your specific requirements.

Leave a comment