Dec-19-2021, 10:59 AM
I suggest to insert the various menus in a collection (here a dictionary named 'menus'). This allows to refer to them more easily, add more of them etc.
Another useful feature is a registering system to register actions to do when the user makes a choice. Try to play with the following extensible code outline to see if you like it
Another useful feature is a registering system to register actions to do when the user makes a choice. Try to play with the following extensible code outline to see if you like it
import re class Menu: def __init__(self, name, value): self.name = name self.value = value self.options = [s[1:-1] for s in re.findall(r'\[[^\]]*\]', value)] def __str__(self): return(self.value) menus = {} menus['main'] = Menu('main', """\ [1] Products [2] Clients [3] Display [4] Report [0] Exit the program.""") menus['products'] = Menu('products', """\ [1] Add new product [2] Product update [3] Delete product [4] Go back to main page [0] Exit the program.""") menus['clients'] = Menu('clients', """\ [1] Add new client [2] Client update [3] Delete client [4] Go back to main page [0] Exit the program.""") menus['display'] = Menu('display', """\ [1] Search list of: [2] Search a: [4] Go back to main page [0] Exit the program.""") menus['reports'] = Menu('reports', """\ [1] Average age of clients: [2] The average price of the products [4] Return to the main menu [0] Exit the program.""") def ask_option(menu): while True: print(menu) opt = input('Please select an option: ') if opt in menu.options: try: return int(opt) except ValueError: return opt else: print(f'Invalid option, please choose one of {menu.options}') registered = {} def register(name, opt): def decorator(func): registered[(name, opt)] = func return func return decorator @register('main', 1) def main_choose_products(menu, opt): return menus['products'] @register('main', 2) def main_choose_clients(menu, opt): return menus['clients'] @register('main', 3) def main_choose_display(menu, opt): return menus['display'] @register('main', 4) def main_choose_reports(menu, opt): return menus['reports'] @register('main', 0) @register('products', 0) @register('clients', 0) @register('display', 0) @register('reports', 0) def all_choose_exit(menu, opt): return None if __name__ == '__main__': menu = menus['main'] while menu: opt = ask_option(menu) func = registered.get((menu.name, opt), None) if func: menu = func(menu, opt) else: menu = menus['main']