What is the best method to perform a menu with submenus (while with breaks or calling menus in functions)? [closed]

1

For a school job, you need to have a menu with several submenus. What is the best way to approach this? I can put the menus inside whiles and go giving break to those whiles when you want to go back to the previous one or separate the menus into functions and go calling when needed. p>

I do not know what would be the best option, I'm open to suggestions, thank you in advance. for example

While 1:

# menu principal
existe()
print("========================")
print("     SA Airlines    ")
print("========================")
print("[1] - Adicionar")
print("[2] - Listar")
print("[3] - Procurar")
print(" ")
res = int(input("Opcao: "))

if res == 1:
    add.adicionar()
elif res == 2:

    while 1:

        # um menu secundario
        print("[1] - Aeronaves")
        print("[2] - Aeroportos")
        print("[3] - Rotas")
        print("[4] - Voltar")

        res = int(input("Opcao: "))
        if res == 1:
            listar.mostraAeronaves()
        elif res == 2:
            listar.mostraAeroportos()
        elif res == 3:
            listar.mostraRotas()
        elif res == 4:
            break;
        else:
            print("ERRO: A opção não se encontra defenida ! tente novamente!")
    
asked by anonymous 21.12.2016 / 14:54

1 answer

2

When you invented functions to program, it is because they are VERY better to organize code and program breakthrough - and this includes organizing the menu structure: you should not think that only the functions at the tips should be functions and that any code on the main body, anyway, serves to make the menus.

If the menus all behave the same way: you have to display a list of options, pick a number and run something else based on that number, the best thing you do is create a generic function to display these menus and get the answer - and then you get all the pre structure of the program very short and separated from the main logic:

aeronaves = []
aeroportos = []


def menu(titulo, opcoes):
    while True:
        print("=" * len(titulo), titulo, "=" * len(titulo), sep="\n")
        for i, (opcao, funcao) in enumerate(opcoes, 1):
            print("[{}] - {}".format(i, opcao))
        print("[{}] - Retornar/Sair".format(i+1))
        op = input("Opção: ")
        if op.isdigit():
            if int(op) == i + 1:
                # Encerra este menu e retorna a função anterior
                break
            if int(op) < len(opcoes):
                # Chama a função do menu:
                opcoes[int(op) - 1][1]()
                continue
        print("Opção inválida. \n\n")

def principal():
    opcoes = [
        ("Adicionar", adicionar),
        ("Listar", listar),
        ("Procurar", procurar)
    ]
    return menu("SA AIRLINES", opcoes)

def adicionar():
    opcoes = [
        ("Aeronaves", adicionar_aeronave),
        ("Aeroportos", adicionar_aeroporto),
        # ...
    ]
    return menu("Adicionar", opcoes)

def adicionar_aeronave():
    aeronaves.append(input("Nova aeronave: "))


def adicionar_aeroporto():
    aeroportos.append(input("Nova aeronave: "))

    #...

def listar():
   ...

def procurar():
   ...

principal()

I used an important feature of Python which is the possibility to pass functions as normal objects - that is, the "menu" function gets its own functions that it should call, in each option, with parameters - and calls the appropriate functions in the line opcoes[int(op) - 1][1]() .

The functions that use the menu define the options as a sequence of items with two other internal items: the first is the printable name of the option, and the second is the function itself, as an object. To do this, just put the function name without adding the ( ) that characterize the function call. (Otherwise Python simply calls the function unconditionally at that point, and adds the value returned by it in the list of options)

So, the line opcoes[int(op) - 1][1]() "says" inside the item "op - 1" of the options, get the second item - that is the function itself (this we declare inside the various functions that declare options to call menu ) and call this object as a function, without parameters.

Note that doing so, if you decide to add a graphical interface for example instead of using prints and inputs, simply redo the "menu" function and the entire program structure continues to function normally.

    
21.12.2016 / 16:42