Keep counter in python

0

Good day.

I am doing a simple program that takes me the sum of each iteration of vehicles, and in the end it shows me the total amount of them. The code I made is the following:

from random import random

nAutos=0
for i in range(3):
aleatorioAuto = random()
if aleatorioAuto > 0 and aleatorioAuto < 0.10:          
    nAutos = 0
elif aleatorioAuto > 0.10 and aleatorioAuto < 0.20:     
    nAutos = 1
    print("Usted ordeno: ", str(nAutos), "Vehiculos")
    nAutos+=1
elif aleatorioAuto > 0.20 and aleatorioAuto < 0.60:      
    nAutos = 2
    print("Usted ordeno: ", str(nAutos), "Vehiculos")
    nAutos+=1
elif aleatorioAuto >0.60 and aleatorioAuto < 0.80:     
    nAutos = 3
    print("Usted ordeno: ", str(nAutos), "Vehiculos")
    nAutos+=1
elif aleatorioAuto > 0.80 and aleatorioAuto < 1:     
    nAutos = 4
    print("Usted ordeno: ", str(nAutos), "Vehiculos")
    nAutos+=1
total=nAutos
print(total)
print("--------------------------Fin del programa---------------------------
")

total, just show me the last iteration you got and add 1. This is the output of the program:

Usted ordeno:  2 Vehiculos
Usted ordeno:  2 Vehiculos
Usted ordeno:  3 Vehiculos
4

If it is generated (2 2 3 vechiculos, the total should throw 7). What is my mistake ?, I hope you can help me. Thanks

    
asked by JUAN RAMIREZ 03.10.2018 в 18:14
source

1 answer

1

You are losing the value that you took by iteration of nAutos If for example nAutos is already 2, and you go back and fall in the case that is worth 3, you are replacing the value, you are not adding it. I edited your code a bit, I think it can work better this way.

from random import random
nAutos = 0
for i in range(3):
aleatorioAuto = random()
if aleatorioAuto > 0 and aleatorioAuto < 0.10:          
    nAutos += 0
elif aleatorioAuto > 0.10 and aleatorioAuto < 0.20:     
    nAutos += 1
    print("Usted ordeno: 1 Vehiculos")
elif aleatorioAuto > 0.20 and aleatorioAuto < 0.60:      
    nAutos += 2
    print("Usted ordeno: 2 Vehiculos")
elif aleatorioAuto >0.60 and aleatorioAuto < 0.80:     
    nAutos += 3
    print("Usted ordeno: 3 Vehiculos")
elif aleatorioAuto > 0.80 and aleatorioAuto < 1:     
    nAutos += 4
    print("Usted ordeno: 4 Vehiculos")
print("Total de autos pedidos: " + str(nAutos) )
print("--------------------------Fin del programa---------------------------
")
    
answered by 03.10.2018 / 18:39
source