Nested Loops and Gilbert and Ilbert’s Scoop Shop Example

I am working on the Gilbert and Ilbert’s Scoop Shop example in nested loops and am trying to explain how it works back to myself.

In this example, why do we set scoops_sold = 0? I

sales_data = [[12, 17, 22], [2, 10, 3], [5, 12, 13]]

scoops_sold = 0

for location in sales_data:
  for element in location:
    scoops_sold += element

Because the += opeartor performs assignment based on the contents of both left and right operands. If you hadn’t pre-defined scoops_sold how could you add to it? You’d have a NameError thrown for scoops_sold because that name did not yet exist. As for the value, we’re using it to count up so there’s a good place to start for this one.

1 Like