Carly's Clippers: Total Revenue; i and range

Hello everyone,

I’ve found loops a little more tricky to get my head around. Below is the example code and the solution

I don’t understand how this code works to get the total revenue based on haircuts last week. When we use range here, what are we actually doing with it? Does it create a temporary list with 0…len? And how does using prices[i] and last_week[i] work to get us the values we want? Why don’t they just iterate from index 0 to index len-1?

Hope that makes sense, it was confusing even writing it! Thanks very much in advance, greatly appreciated

I understand! It certainly can become confusing. :slight_smile:

range() will iterate through a list a specific number of times, in this case, the len of the list “hairstyles.”

for i -------for temporary variable (the indexed item)
in range(len(hairstyles)) ------ loops through the length of the list/accesses each item in that list by its index.

And then the variable total_revenue is equal to the running total of the length of the items of the prices list * the items of last_week. [i] is the indexed item of each list. ex: 30 * 2, 25 * 3, etc until it reaches the end of both lists.

As you go along in the modules one thing to maybe start doing is break down the directions into words that you understand & then write comments in the code for each line, explaining what the code is doing (or what you want it to do). I do that sometimes and it helps.

This might help:


1 Like

Thanks for the speedy reply Lisa!

That makes a lot more sense, so in essence the range(len) allows us to use the common index across lists in calculations?

The break down idea really helped to be honest, it made a lot more sense after doing that. Took a lot longer but worth it while learning it in particular thank you!

1 Like

It, range() iterates the entire length of the object starting at 0 index to the length of the object up to -1 (which would be the last index of the object.)

It does take a little longer to break down questions, but, it helps you make sense of what you’re doing if you can write it in words you understand. I still do it. :slight_smile:

1 Like