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.