A register of people in python

Asked

Viewed 8,232 times

-1

I was looking to make a record of people with id, nome and idade, created this code. The problem is in option 2, when show. I wanted to show like this:

print("nome",nome_pessoa,"idade",idade_pessoa,"id",id_pessoa)

but the way it is I can’t control the way I quoted above.

Does anyone know how to fix it, or is there a better way to do that? I also wanted to know if you have how to show the data of a specific person as you ask option 3

listas = [[]] #uma lista de lista

while True:
    print("1-Cadastrar pessoa")
    print("2-Lista Cadastros")
    print("3-Procurar Pessoa Especifica")
    op = int(input())#Escolha da opcao
    if op == 1:
        nova = [] # cria uma lista para adicionar o id, nome e idade da pessoa
        id = input("Id da pessoa")
        nome = input("Digite o nome da pessoa")
        idade = input("Idade da pessoa")
        nova.append(id)
        nova.append(nome)
        nova.append(idade)
        listas.append(nova)#Adiciona a lista criada com o cadastro da pessoa dentro da lista

    elif op == 2:
        for mostrar in listas:
            for mostrar2 in mostrar:
                print(mostrar2)#mostra tudo dentro da

    elif op == 3:
        print("pensando")

3 answers

4

I believe that the problem has been solved in the other answers, but I will leave here a suggestion of how I would solve the problem if you are interested to study an alternative.

First, you have 4 well-defined tasks in your project:

  1. View the menu;
  2. Option 1, to register a person;
  3. Option 2, to list registered persons;
  4. Option 3, to search a person’s data;

Why, then, not create a function for each?

Displaying the menu...

def exibir_menu():
    print('''Escolha uma opção:

    1. Cadastrar uma pessoa
    2. Listar pessoas cadastradas
    3. Procurar dados de uma pessoa
    ''')

Registering a person...

def cadastrar(pessoas):
    identificador = input('Id? ')
    nome = input('Nome? ')
    idade = int(input('Idade? '))
    pessoas.append((identificador, nome, idade))

The considerations would be:

  • Do not use an object called id, because it is the name of a native Python function;
  • The value of idade is converted to integer as it is a number - this will facilitate in case you need to sort the list by age;
  • A tuple was created with the data - note the presence of two parentheses in append;

The use of the tuple follows the same logic that you used with the list, to store the values grouped, but with tuple the code becomes more semantic.

When to use lists and when to use tuples?

Listing people...

def listar(pessoas):
    for pessoa in pessoas:
        identificador, nome, idade = pessoa
        print(f'Nome: {nome}, idade: {idade}, id: {identificador}')

Here, I use the tuple deconstruction to pass the tuple pessoa, that has the three information of the person, for three different variables; thus, the code will be much more readable, because it is easier to understand that nome is the name of the person to whom pessoa[1]. And to display the information, I used the f-strings, from Python 3.6 - where, for example, {nome} shall be replaced by the value of nome.

Seeking a person...

def buscar(pessoas):
    identificador_desejado = input('Id? ')
    for pessoa in pessoas:
        identificador, nome, idade = pessoa
        if identificador == identificador_desejado:
            print(f'Nome: {nome}, idade: {idade}, id: {identificador}')
            break
    else:
        print(f'Pessoa com id {identificador_desejado} não encontrada')

Which basically scrolls through the list of people searching for the desired id and when you find it, displays the person’s information, otherwise the message is displayed that the person has not been found.

Putting it all together...

So the code would look something like:

def main():
    pessoas = []

    while True:
        exibir_menu()
        opcao = int(input('Opção? '))
        if opcao == 1:
            cadastrar(pessoas)
        elif opcao == 2:
            listar(pessoas)
        elif opcao == 3:
            buscar(pessoas)
        else:
            print('Opção inválida')

See working on Repl.it

This already greatly improves the readability of the code and facilitates the maintenance of the project. Even so, it is important to point out that much could be improved; for example, the reading of the data is being carried out within the function, along with the logic of registering - ie, are two responsibilities for the same function, this is not always good to do, because it makes it impossible for you to use the function elsewhere (and if I want to register a person who already knows the data? It would have to create another function, duplicating the logic of registration, which hurts the principles of DRY).

The same thing happens with the other functions, for example. What if I want to send the full list by email instead of showing it on the screen? It would take a different function than listar that would have a very similar logic.

Another trivial change to be made that would greatly improve the readability of the code would be to use namedtuple, instead of just tuples, thus dispensing with the need to deconstruct the tuple for variables.

That said, I leave open these improvements for, in case you, or whoever is reading, search on their own to elaborate such improvements in the code and, if you do, post as answer here, because it will be useful for many users.

  • I guess I kind of understood, I started one day of this, what is this def?

  • @Nathansilva is used to define a function

  • is equal to function in c? or a method in java?

  • @Nathansilva the function in C, yes. The Java method already changes conceptually, but resembles quite.

  • Thank you, I’ll read about, I got interested on this.

2


Option 2: To format prints you can do so:

elif op == 2:
    for mostrar in listas:
        try:
            print("Nome: %s - Idade: %s - ID: %s"%(mostrar[1],mostrar[2],mostrar[0]))
        except:
            print("Essa pessoa não possui algum dos valores a seguir: Nome, Idade, ID")

If the value of one of the variables is an integer, you exchange %s for %d, if it is a float, you must exchange %s for %f.

Option 3:

id = input("Digite o id da pessoa desejada: ")
for mostrar in listas:
    if id in mostrar:
        try:
            print("Nome: %s - Idade: %s - ID: %s"%(mostrar[1],mostrar[2],mostrar[0]))
        except:
            print("Essa pessoa não possui algum dos valores a seguir: Nome, Idade, ID")
  • you’re making that mistake

  • Traceback (Most recent call last): File "/home/Nathan/Pycharmprojects/Aula/Aula.py", line 19, in <module> print("Id: %s, Name: %s, Age: %s"%(show[0],show[1],show[2])) Indexerror: list index out of range

  • i registered and printed out the list. Exit: [[['1', 'aaa', '1'], ['2', 'bbb', '2'']]

  • all right buddy.

  • thank you very much friend, another question, how would you remove this void?

  • thank you very much, I got!

  • a doubt. The solution of the 2 is not certain.

  • Edited, try it again

Show 3 more comments

0

Use print() with formatting options:

print("Id: %s, Nome: %s" % (mostrar2[0], mostrar2[1]))

The %s option can have more arguments such as a minimum size: %S20

  • I tried that and it didn’t work out

Browser other questions tagged

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