K
Rafael,To put the message 'not registered product' If the list is empty, you can create a condition in the function lista that checks the list (compras) before effecting the print loop, using for example the not:if not compras:
print("\nProduto não cadastrado")
Already to make the output in the formatting you want, your code seems already very close, missing just listing the products, to have access to the product index, you can use the function https://docs.python.org/3/library/functions.html#enumerate , using it in its form, having access to the product and also to the index of the list:for i, e in enumerate(compras):
The first position is the index and the second is the element of the list.With this you can change your function mostra_dados to display the product number:def mostra_dados(produto, preco, numero):
print('\nProduto: {}\nNome: {} \nPreço: {}' .format(numero, produto, preco))
Remembering that the Python index starts at zero, before sending the value to the function mostra_dados, sum up one to the value of the index:mostra_dados(e[0], e[1], i + 1)
Now it is to gather everything, having a result more or less as follows:compras = []
valores=[]
def pede_produto():
return (input("Produto: "))
def pede_preco():
return float(input("Preço: "))
def mostra_dados(produto, preco, numero):
print('\nProduto: {}\nNome: {} \nPreço: {}' .format(numero, produto, preco))
def novo():
quantidade = int(input('Quantos produtos que comprar? '))
for x in range(quantidade):
print('Produto e Preço', x + 1)
produto = pede_produto()
preco = pede_preco()
compras.append([produto, preco])
valores.append(preco)
def lista():
if not compras:
print("\nProduto não cadastrado")
else:
print("\nCompras\n\n------")
print('Quantidade: {}'.format(len(compras)))
print('Total',sum(valores))
for i, e in enumerate(compras):
mostra_dados(e[0], e[1], i + 1)
def valida_faixa_inteiro(pergunta, inicio, fim):
while True:
try:
valor = int(input(pergunta))
if inicio <= valor <= fim:
return (valor)
except ValueError:
print("Valor inválido, favor digitar entre %d e %d" % (inicio, fim))
def menu():
print("""
1 - Novo
2 - Lista
0 - Sai
""")
return valida_faixa_inteiro("Escolha uma opção: ", 0, 3)
while True:
opção = menu()
if opção == 0:
break
elif opção == 1:
novo()
elif opção == 2:
lista()
See online: https://repl.it/repls/GlassZigzagProfiler