I go into an ice cream store, they have 5 flavors of ice cream (vanilla, chocolate, strawberry, pecan, raspberry).
They give free samples. So I tell the worker for every flavor of ice cream you have, can I please have a free sample?
And so the worker will go through all the flavors individually and give me a sample. At every point, I am only taking in 1 flavor at a time.
The code for this looks like
ice_cream_menu = ['vanilla', 'chocolate', 'strawberry', 'pecan', 'raspberry']
for flavor in ice_cream_menu:
sample(flavor)
#sample is a made-up function for the sake of this narrative
#the specific order I will sample the flavors is the order from the list
Now, it’s crucial that one is comfortable with playing around with different variants of the first example… we could just as well write:
ice_cream_menu = ['vanilla', 'chocolate', 'strawberry', 'pecan', 'raspberry']
for chicken in ice_cream_menu:
sample(chicken)
#this is the same code
but it is hard to understand (and a disgusting visual mix), so we try to choose semantically accurate variable names (and if we can’t efficiently come up with it, single-letter variable names, i, j, etc…)
Finally, once you practice enough to get used to that, the narrative changes. My friend tells me, that my favorite ice-cream shop is not the best in town. I heavily disagree. There’s only one way to find out. We go to all 3 shops in town. Conveniently they all have the same menu. We try all 5 different flavors to be scientific.
The code would look like this:
ice_cream_shops = ["ben_jerrys", "haagen_daaz", "ciaobella"]
ice_cream_menu = ['vanilla', 'chocolate', 'strawberry', 'pecan', 'raspberry']
for shop in ice_cream_shops:
for flavor in ice_cream_menu:
sample(flavor)
# we will go to each shop in the order listed,
# and in each shop sample the flavors in the order listed.
It’s a silly example, and not actually fully accurate in our narrative since we would have to use classes to assign each menu to each shop (to properly give a “rating” to each one). But what it does show is that we did eat all 5 flavors in all 3 locations. I hope it gives you an idea of how loops can be visualized.