What does this python code do?

im in the loops section of python now.
im really confused by what this code does. i really dont understand what it does so the outcome is 96.
is there someone who can explain what the parts of this code do?

There’s a bug in that code! Look at the second loop for i in location:, does it make sense what the += is doing there?


i dont think so, do you mean i could also use the + on itself? im kinda new to all this so not that good atm :stuck_out_tongue: im using the += because code academy told me to use it.

The += means add the value on the right to the value stored in the variable to the left, then store that value in the variable on the left. Is that what you want to be happening?

1 Like

i think i have to switch the sides.


but can you tell me what the codes does ? (in parts)
i cant translate what the code does by myself.
i really want to know because i think i will understand it better then.

1 Like

Step 1

You are given an array called sales_data
You want to compute the total when you sum all the numbers in this array

Notice that this array’s elements are arrays themselves
element 1: [12, 17, 22], element 2: [2, 10, 3], element 3: [5, 12, 13]

Step 2

Define a variable that will hold the total of scoops sold: scoops_sold = 0
As you count through array sales_data, store the total in scoops_sold

Step 3

Loop through array sales_total with a for loop: for location in sales_data:
Remember that you have arrays as elements, so location will hold the values:
[12, 17, 22], [2, 10, 3], and [5, 12, 13] every iteration of the loop

Step 4

Since location is holding arrays, you need a second for loop to traverse these for i in location:
This will be a nested loop inside the first loop. That means all iterations of this loop will execute before the outer loop moves on.
For example, the outer loop will do location = [12,17,22] first.
Then your nested loop will do: i=12, i=17, and i=22 before the outer loops updates to location = [2, 10, 3]

Step 5

Now that you finally have access to the individual numbers, you want to accumulate them (add them together). So your code should do: scoops_sold = scoops_sold + i
This way every value that i takes will be added to your total that you are storing in scoops_sold.
Also, python has a neat way of doing this sort of accumulation like this: scoops_sold += i
It means the same as the longer expression, but is easier to read and concise

Step 6

Once your loops have finished and you have computed a total, display the result with print(scoops_sold)

I hope this helps! :+1: