Delete and Query Python function

Asked

Viewed 1,459 times

0

I have to make a simple program in Python. In the case of a library , however I’m having difficulties in the function of consulting and deleting. I honestly stalled, tried a lot of different ways but I couldn’t.

My code is like this, what my mistake ?

livro=[]
opc = 0
i = 0

def incluirLivro():
    idLivro=[]
    print("Digite o id do Livro")
    idLivro.append(int(input()))
    livro.append(idLivro)
    titulo=[]
    print("Digite o titulo do Livro")
    titulo.append(input())
    livro.append(titulo)
    autor = []
    print("Digite o autor do Livro")
    autor.append(input())
    livro.append(autor)
    editora = []
    print("Digite o editora do Livro")
    editora.append(input())
    livro.append(editora)
    volume = []
    print("Digite o volume do Livro")
    volume.append(int(input()))
    livro.append(volume)
    ano = []
    print("Digite o ano do Livro")
    ano.append(int(input()))
    livro.append(ano)
    preco =[]
    print("Digite o preco do Livro")
    preco.append(float(input()))
    livro.append(preco)

def consultarLivro():
    id = int(input())
    for i in livro:
        if id == livro[i]:
            print(livro[i])
def excluirLivro():
    print('Informe o ID do livro que você deseja excluir')
    idLivro1 = int(input())
    if idLivro1 == livro[i]:
        del(livro[i])


while(opc != 5):
    print("\nMenu do livro\n\n")
    print("\n1 - Incluir\n")
    print("\n2 - Consultar\n")
    print("\n3 - Alterar\n")
    print("\n4 - Excluir\n")
    print("\n5 - Fim\n")
    print("\nDigite uma opção")
    opc = int(input())
    if(opc==1):
        incluirLivro()
    if(opc==2):
        consultarLivro()
    if(opc==3):
        alterarLivro()
    if(opc==4):
        excluirLivro()
    if(opc==5):
        print("Fim do programa......")

2 answers

1

the function consultarLivro is resolved as follows:

adding range(len(livro)).

This solves why the list index only works with numbers and not with strings that’s what you were doing.

Example:

livro[0], that would return the first element of the list, and then compare.

What were you doing : livro['Titulo'], which would be functional if it were a dictionary.

Another change I made was for a [0] the front of livro[i], the reason was that you made all content of livro were lists, see:

[[299], ['t'], ['a'], ['e'], [12], [2017], [1.99]] # Retirado do console

Then it runs smoothly, but you just asked to print the book again[i], basically asking to print the ID again(?).

getting:

def consultarLivro():
    id = int(input('Digite o ID:'))
    for i in range(len(livro)):
        if id == livro[i]:
            print(livro[i])

and the exit:

>>> [299]

The function excluirLivro() was basically the same thing. I added the for and then he deleted, but he only deleted the ID, which is wrong, but now he deletes something.

def excluirLivro():
    print('Informe o ID do livro que você deseja excluir')
    idLivro1 = int(input())
    for i in range(len(livro)):
        if idLivro1 == livro[i][0]:
            del(livro[i])
            break # Quando deletar, ele para o For, senão vai causar um erro.

livro before : [[299], ['t'], ['a'], ['e'], [12], [2017], [1.99]]

livro afterward: [['t'], ['a'], ['e'], [12], [2017], [1.99]] # Deletando apenas o ID

Well, what I did above was just take out the bugs in your code, but it still goes wrong somehow because it doesn’t fully print the book, well, there it is with you.

If you want a hint, create a dictionary, and each dictionary value will have an ID of each book, and within each ID will have its values ( Title, etc... ), example:

livros = {"299":["Titulo","Autor","Editora",2,2017,1.99],
"212":["Titulo2","Autor2","Editora2",2,2017,1.99]
}

I hope I helped make your code clearer.

  • It’s not working, nothing '-' appears and in the delete I’m having trouble deleting everything anyway

  • The right thing is actually to redo all your code and base it on dictionaries, by lists it’s impossible, I think.

0

Pay attention to the scope of variables in your program.

I have seen several lists that are created changed but die after function call because no function of yours has return value.

I’ll give you a simple example to understand scope and then you can try to look for the error or errors in your code and tell me.

x = 5
def foo():
    x = 10
foo()
print(x) # valor printado é 5 pois a variável x de dentro da função só existe la dentro, não é possível acessá-la no programa principal.

Another example:

def foo1()
    var1 = 15
foo1()
print(var1) # Erro de sintaxe, variável var1 não existe.

If you want the variable to exist outside a function you need it to RETURN one or more Ex values.:

def foo2()
    var2 = 13
    return var2
var2 = foo2() # faz a variável var2 receber o valor de retorno da função e existir fora do escopo de foo2. (O nome dessa variável não importa, poderia ser var0 = foo2() que daria na mesma)

To conclude. You can return multiple values in the same function by separating each variable (expression to be more exact) by comma.

Example:

def insereLivro():
    lista_livro = ['l1', 'l2', 'l3']
    lista_precos = [10, 20, 500]
    lista_editora = ['e1', 'e2', 'e3']
    return lista_livro, lista_precos, lista_editora
lista_livro, lista_precos, lista_editora = insereLivro()  # Novamente, os nomes das variáveis nesse linha podem ser diferentes dos nomes da função retorno, x1, x2, x3 = insereLivro() iria dar na mesma.

EDIT: One more thing, when working with lists, which are mutable data structures, if any list is passed by parameter to some function, the passage is made by reference, that is, if you pass a list per parameter to a function and within that function make changes to that list, those changes will be reflected in the global scope, even if the list is not returned using the command return.

def appendlista(lista)
    lista.append(10)
lista = [1,2,3]
print(appendlista(lista)) # Resulta em [1,2,3,10]

Browser other questions tagged

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