11. Loops#
A loop is a programming concept that allows us to execute some commands over and over again. To demonstrate the use of a loop imagine that you have a bag of balls, some of which are coloured red and the others coloured blue. You want to count the number of blue and red balls that are in the bag. The steps to do this are:
Remove a ball from the ball
If the ball is red, add 1 to a count of the red balls and place the ball to one side
Else add 1 to a count of the blue balls and place the ball to one side
Repeat steps 1 to 3 until there are no balls left in the bag.
This is an example of how we would use a loop in programming. Here we did not know how many balls there were in the bag so we had to repeat steps 1 to 3 while there are still balls in the bag. If we did know how many balls were in the bag then we could repeat steps 1 to 3 for each ball. So there are two types of loops: for loops and while loops.