Custom menu

Asked

Viewed 66 times

0

I’m creating a simple script with a def I printed out a custom menu. The first parameter is the header, followed by the number of items accessible by the menu and finally a third parameter that is unpacked in the function, representing the menu calls. It’s just a workout, nothing as useful as that, but I feel that what is being delivered is not the most elegant solution, although it simplifies a lot. There may be confusion with the number of items and all the elements typed for the last parameter. Does anyone have a better idea? Perhaps with a higher or more elegant, functional complexity level, etc.. Or is that what you think the proposed solution would be? Follows the script:

def personalizado(txt, itens, *chamadas):
    print('-=-' * 15)
    print(txt.center(45))
    print('-=-' * 15)
    print()
    for c in range(0, itens):
        print(f'{c +1} - {chamadas[c]}')


# teste protegido
if __name__ == '__main__':
    personalizado('MENU QUALQUER', 6, 'Acessar', 'Visualizar', 'Cadastrar',
                  'Deletar', 'Reiniciar', 'Exit',)

The result:

-=--=--=--=--=--=--=--=--=--=--=--=--=--=--=-
                MENU QUALQUER                
-=--=--=--=--=--=--=--=--=--=--=--=--=--=--=-

1 - Acessar
2 - Visualizar
3 - Cadastrar
4 - Deletar
5 - Reiniciar
6 - Exit

1 answer

2


A suggestion would be to remove the second parameter (itens) of function personalizado, because as you receive in the third parameter a tuple, you can iterate in it and discover the amount, with this, your for could look like this:

for index, chamada in enumerate(chamadas):
    print(f'{index + 1} - {chamada}')

As an example, using the enumerate to already have access to the index.


Other things you can do like learning and testing would be:

Decrease the number of function calls print, it is possible to use the parameter sep, thus passing several parameters to it and the separation would be a line break:

print('-=-' * 15, txt.center(45), '-=-' * 15, '', sep='\n')

Create the loop in one line only:

#list comprehension
[print(f'{index +1} - {chamada}') for index, chamada in enumerate(chamadas)]

#join da string que contém a quebra de linha
print('\n'.join(f'{index +1} - {chamada}' for index, chamada in enumerate(chamadas)))

I found the use of the parameter *chamadas well cool, the function call becomes simpler, not having the need to create the list.


Online example: https://repl.it/repls/HelpfulPersonalPlan

  • 1

    Good @Danielmendes, that’s what I was looking for. Avoid redundancies, I ended up observing these changes yesterday. I was looking for a way to printar online too, it was perfect! Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.