Understanding loops

You are probably viewing this because you have just started programming and are trying to figure what these loops are all about. Well, you have come to the right place.
First off, loops are something you find in most programming languages, so once you get a hold of it, it is easy to pass on when you learn another new programming language later.
In programming we use two different loops: the for loop and the while loop.
Why do we need two loops? Good question. In reality they are more or less interchangeable, and you use the one that you figure out works best for the task you are trying to accomplish.
In this post we will be looking at understanding the for loop.Recycle
A loop in programming is just repeating itself (looping) – meaning we want to do something multiple times. You can think of it as recycling. You go buy a bottle of beer, drink it and the bottle gets recycled before it pops up in another shop (sequence) a few days later.
The loop will “walk its way through” until it reaches the end of the sequence before it stops.
Below we have 8 bottles and we will name them from left to right:
A, B, C, D, E, F, G, H.
The bottles are our sequence in this example thus we have 8 bottles in our sequence.
Beer

Example 1:

In our first example we will let each of the bottles in our sequence type the word “Beer” once. Since we have 8 bottles in our sequence this means that it will print out the word “Beer” a total of 8 times.
[code language=”python”]
for _ in ‘ABCDEFGH’:
print(‘Beer’)
[/code]
Result:
[code language=”python”]
Beer
Beer
Beer
Beer
Beer
Beer
Beer
Beer
[/code]
Want to print it 3 times instead? – Well, then just make your sequence shorter by taking out 5 bottles leaving 3 behind: A, B and C.
[code language=”python”]
for _ in ‘ABC’:
print(‘Beer’)
[/code]
Result:
[code language=”python”]
Beer
Beer
Beer
[/code]
The key for understanding the for loop is to think sequence. Let’s try another example. This time we name our bottles 1 and 2:
[code language=”python”]
for _ in ’12’:
print(‘Beer’)
[/code]
Result:
[code language=”python”]
Beer
Beer
[/code]

Example 2:

Let’s try to put one loop inside of another loop and see what happens.
[code language=”python”]
for _ in ’12’:
for _ in ‘ABC’:
print(‘Beer’)
[/code]
Result:
[code language=”python”]
Beer (Round 1)
Beer (Round 1)
Beer (Round 1)
Beer (Round 2)
Beer (Round 2)
Beer (Round 2)
[/code]
As you can see this prints “Beer” 6 times. Why? Because we have two loops: the first has a sequence of 1 and 2 = 2 times. The second has a sequence of A, B and C = 3 times.
What happens is that the first loop will run once and this will trigger the second loop to start it’s sequence. This will print “Beer” 3 times.
Then the first loop will go back and run the last sequence “2” which will again trigger the second loop: hence 2 x 3 = 6
Hope this helps

Leave a Comment