The best way to make an information search program

Asked

Viewed 51 times

-1

I work with text production and would like to make a search program that returns pre-formatted information so that I only copy and paste in the text editor.

I’m a beginner in Python, so my script is very rudimentary. I did the following:

_joao = 'João Silva, nascido na cidade tal, é engenheiro, ...'
_pedro = 'Pedro da Silva, nascido na cidade tal, é empresário, ...'

nome = ''
while nome != 'sair':
    def busca():
        nome = input('Digite um nome a ser buscado ou digite "sair" para fechar o programa: ')
        if nome == 'joao':
            print (_joao, '\n')
        elif nome == 'pedro':
            print (_pedro, '\n')
        elif nome == 'sair':
            exit()
        else:
            print ('Nome não encontrado')
    busca()

What is the best way to do this kind of program?

  • 2

    The best way to program is to follow the standards set by the community, your question is very comprehensive, there is some error in the code?

1 answer

0


You do not need to define a function within the loop, or it will be created every time you repeat. The function could be outside the loop, or it simply doesn’t need a function in this simple example.

A very useful data structure for what you want to do, would be the dictionary - it allows you to associate each key to an object - then allows you to efficiently retrieve the object in any order from the key:

dados = {
    'joao': 'João Silva, nascido na cidade tal, é engenheiro, ...',
    'pedro': 'Pedro da Silva, nascido na cidade tal, é empresário, ...',
    'douglas': 'Douglas 1Alc, nascido na internet, é usuário do SOpt...',
}

Once the dictionary is defined, just use it instead of several ifs:

while True:
    nome = input('Digite um nome a ser buscado ou "sair" para fechar o programa')
    if nome == 'sair':
        break
    print(dados.get(nome, 'Nome nao encontrado!'))

In the future, if the number of names increases greatly, it is better to use a database such as the sqlite to store the data instead of a dictionary.

  • nosklo, thank you so much for your help. It’s working. Obg

  • It is possible to use more than one key, like: João, Joao, JOÃO?

Browser other questions tagged

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