2
As you can see in the code below I have tried several ways to make each product inserted to create a new code with codigo += 1
, but is returning:
Unboundlocalerror: local variable 'code' referenced before assignment!
Putting this line as a comment and following the code I get a problem in the insertion of the product data entered by the user on arquivo.txt
.
I’ve tried with for
, 1 by 1 and I’m not getting through. If you add 1 item only with the name filled and with the quantity, prices and total commented adds normally, but more than 1 already returns the error of except..
Thank you for your attention.
import time
arquivo = open('arquivo.txt','w')
quantidade = codigo = 0
produto = ""
preCompra = preVenda = total = 0
def menu():
print("Digite a opção desejada: \n0. Sair do programa\n1. Adicionar produto\n2. Remover produto")
opcao = int(input("Que opção você escolhe? "))
if opcao < 0:
print("Esta não é uma opção válida!")
elif opcao == 0:
print("Saindo do programa!")
exit
elif opcao == 1:
addProduto()
elif opcao == 2:
print("Você escolheu a opção 2!")
else:
print("Você deve escolher um dos itens da lista!")
def addProduto():
#codigo += 1
produto = str(input("Qual o nome do produto? "))
quantidade = int(input("Quantos produtos? "))
preCompra = float(input("Qual o preço de compra? "))
preVenda = float(input("Qual o preço de venda? "))
total = float(preCompra * quantidade)
produtosAdd = [produto, quantidade, preCompra, preVenda, total]
try:
'''for pro in produtosAdd:
arquivo.writelines(produtosAdd)
arquivo.close()'''
arquivo.write(produtosAdd)
print("Produto adicionado com sucesso!")
except:
print("Ocorreu um erro!\n")
time.sleep(5)
menu()
if __name__ == "__main__":
menu()
I edited the question because your Portuguese was very confused, in case I interpreted something wrong feel free to re-edit the question.
– lazyFox
Vinicius, in your commented code that inserts in the file, you called the
arquivo.close
. If you close the file, how do you expect to add more data to it?– Woss
Sorry, it was a glitch after a few attempts, but even removing the.close() file from the loop or even commenting on the line, it doesn’t work. The problem is adding more than one variable at the same time in the file. Thank you Anderson.
– Vinícius
Then do the following: edit the question and put EXACTLY the code you are running and describe what is happening, such as describing what data would be written in the file and what, in fact, was written.
– Woss
It has already been edited.. It should be written in the document the variables that are inside the product variableAdd, but returns except.
– Vinícius
Vinicius, it is not a good thing you capture the exception in this way and present a generic message. You will never know what is wrong. Aim to capture the exception and display the exception’s message.
– Woss
Got it! Thanks for the help Anderson! I was trying to add as dictionary, which is not allowed at the time I converted to string, was.. Hug.
– Vinícius