Sum variable is accumulating the value instead of starting at zero

Asked

Viewed 97 times

1

The algorithm is for the customer to place orders in a snack bar, he asks for the name of the customer - 1, then the order quantity and then the algorithm asks to enter the order number, when the order closes the program gives the total order value and passes to next customer - 2, when the client - 2 terminates the order the algorithm takes the total value of client 1 sum with client 2 and the total value of that sum for client 2 instead of only the pure value for client 2

print('-' * 20)
print('{:^20}'.format('LANCHONETE'))
print('-' * 20)
print('''Cardapio
[1] - Esfirra R$ 3,50
[2] - Coxinha R$ 3,50
[3] - Hotdog R$ 4,00
[4] - Hamburgue R$ 7,00
[5] - Suco R$ 1,50''')
valor = soma = 0
while True:
    print('-' * 20)
    nome = str(input('Digite seu nome: '))
    quant = int(input('Digite a quantidade do pedido: '))
    print('-' * 20)
    for c in range(1, quant + 1):
        pedido = int(input(f'Digite o {c}° pedido: '))
        if pedido >= 1 and pedido <= 2:
            valor = 3.50
        if pedido == 3:
            valor = 4
        if pedido == 4:
            valor = 7
        if pedido == 5:
            valor = 1.50
        soma += valor
    print(f'O valor total do pedido é R${soma:.2f}')

1 answer

2

That’s because you started the value of soma out of the loop, then the value will accumulate during the iterations. What you need to do is start the soma at zero for each new client, within the repeat loop.

Instead of:

soma = 0
while True:
    ...

Do:

while True:
    soma = 0
    ...
  • It worked out thanks!

  • Don’t forget to evaluate the answer

Browser other questions tagged

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