# incrementar el valor base python for loop

How do I increment a base value each time "i" is looped in a for loop? The logic is something like:

``````fruits = [bananas, apples, pears]
total_fruits_count = 0

for i in fruits:
## some code resolveing fruit count ##
local_fruit_count = 1
total_fruits_count + local_fruit_count

print total_fruits_count
``````

With this code, total_fruits_count just ends up being 0. How is this possible?

preguntado el 17 de mayo de 13 a las 08:05

## 3 Respuestas

You need to modify the value of `total_fruits_count`.

``````fruits = ["bananas", "apples", "pears"]
total_fruits_count = 0

for i in fruits:
local_fruit_count = 1
total_fruits_count += local_fruit_count

print total_fruits_count
``````

In your original code, you did `total_fruits_count + local_fruit_count`, which calculates the sum of the two, but doesn't do anything with it. the plus-equals shortcut `+=` adds the values and stores it in the left variable, `total_fruits_count`.

contestado el 17 de mayo de 13 a las 08:05

Thanks. Great explanation aswell! - Arash

@Arash If you liked my answer, could you please clicked the upvote triangle above the 0 vote count and the checkmark under it? Thanks! - Serpientes y Café

This just calculates the sum and discards the result

``````total_fruits_count + local_fruit_count
``````

Necesitas el `=` in there to assign the result back to `total_fruits_count`

``````total_fruits_count += local_fruit_count
``````

contestado el 17 de mayo de 13 a las 08:05

I think You can use enumerate function or len depending on what You need

``````fruits = ["bananas", "apples", "pears"]
for i, fruit in enumerate(fruits):
print "fruit with index %d is '%s'" % (i, fruit)

total_fruits_count = len(fruits)
``````

contestado el 17 de mayo de 13 a las 08:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.