Loops

When you write code, you might notice that you need to execute some code several times in the same or in a similar way. This could be because you need to check the value of some variables or because you do the same thing for all elements of a list.

Why using Loops

Here are some examples of code snippets that would repeat the same action (or similar).

names = ["Thomas", "James", "Nicolas"]

print("Hello, " + names[0] + "!")
print("Hello, " + names[1] + "!")
print("Hello, " + names[2] + "!")

if (names[0] == "Henry"):
    print("One of these gentlemen is called Henry Ford, correct?")
if (names[1] == "Henry"):
    print("One of these gentlemen is called Henry Ford, correct?")
if (names[2] == "Henry"):
    print("One of these gentlemen is called Henry Ford, correct?")

The examples above are typical code lines that are repeated over a certain number of times. The first example is printing the same text with different names while the second part if comparing different entries one after the other as a sequence. For 3 entries, this is no issue, but what if there is a list with 100 entries? Or even 1000? Would you then copy the same code 1000 times? Or even worse, what if the exact number is not known in advance? How to know how many times to repeat the code?

The solution for this issue would be to use loops. A loop is repeating the same thing several times and is made of several key elements: the starting point, the end point, the step size between the iterations and the code that is actually executed.

There are two types of loops: for loops and while loops. The for loops are mainly used for repeated actions with an end point after a predefined number of so called iterations. An iteration is the single execution of the code that will be repeated. So each time the same code is running another time, a new iteration is being executed. The while loops often end due to an external (or internal) condition that is often independent from the exact number of iteration. This is often used to stop a loop after an event like a button press is triggered or when a certain measurement value has been reached. Sometimes, a while loop is used to replace a for loop but to have even more control about the end point or the step size.

For Loops

The syntax of a for loop is as such:

for i in range(start_point, end_point, step_size):
    print("Execute code here several times!")

Note that the letter i here is often used to indicate the iterator, which is a variable that changes for each iteration based on the starting point, the end point and the step size. The iterator starts with the value defined as the starting point and it will end with the value defined as the end point. Then, it will increase (or decrease) after each iteration with the value defined as the step size. Also, note that the code that should be executed is indented (shifted to the right compared to the line above) to indicate which lines belong to the loop and which are not. (This is actually very similar to the conditional statements.)

The printing example at the top can therefore be written as follows:

names = ["Thomas", "James", "Nicolas"]
for i in range(0, 2, 1):
    print("Hello, " + names[i] + "!")

The code above will start with i=0 and it will increase i by the number 1 after running the code for the first time, then it runs a second time with i=1 and the iterator will be increased again. Then it runs the code again with i=2 and after that it stops. The variable i in the print statement is used as the index to indicate which name of the list we want to print.

The second part of the example can also be replaced by a loop structure combined with a nested conditional statement:

names = ["Thomas", "James", "Nicolas"]
for i in range(0, 2, 1):
    if name[i] == "Henry":
        print("One of these gentlemen is called Henry Ford, correct?")

The code above will iterate through each name in the list and check if it is equal to the value “Henry” and if it is, it will print a message. The advantage now is, that the code can easily be adapted if the list of names will be bigger.

Just like nested conditional statements, you can have nested loops. They can be either nested inside another loop, or nested inside a conditional statement. For example you could have an if-statement and inside this statement, you could have a loop.

iterations = 4
if iterations > 1:
    for i in range (1, iterations, 1):
        print(his is iteration number " + i + "!")

A very interesting case for nested loops inside loops would be if you want to go through a 2D matrix for example:

points = [[1, 3], 
          [1, 5], 
          [3, 1],
          [2, 2]]
for i in range(0, 3, 1):
    for j in range(0, 1, 1):
        points[i][j] = 0.0

The code above will set every element inside the given 4×2 matrix to 0.0 as it goes through both loops. This is often used for vision application to go through an image matrix.

The for loop can not only be used to go through a range of numbers, but it can also be used to go through a list directly. So instead of using for i in range(0,2,1) you can also write for i in names which will then go through each element of the list and execute the code. This is especially useful when the length of the list is not known and this is a very elegant way to solve this. (It is also considered the Pythonic way to use the for loop.)

names = ["Thomas", "James", "Nicolas"]
for name in names:
    if name == "Henry":
        print("One of these gentlemen is called Henry Ford, correct?")

Note that the example above uses a different name for the iterator as i is not very descriptive. Also, you now don’t use names[i] but the variable name used for the iterator name.

While Loops

While loops are slightly different and probably less obvious. They can perform the same task with some more manual intervention than a for loop. Just like the for loops, a while loop also has a starting point and an end point. The starting point is the first time that the loop is being executed. The end point is the last time that it is being executed. Unlike for loops, there is not necessarily a fixed amount of iterations that the while loops are running through. The loop ends after a certain condition is not fulfilled anymore. The only explicit parameter that a while loop has is a condition that is specified at the beginning. This condition must have a boolean state, either true or false.

The syntax is as follows:

condition = True
while (condition == True):
    print("Execute code here several times!")

The above loop will run forever. This is because there is no possibility that the condition that is checked before each new iteration will ever change its state. As a result, the condition will be always true and the loop will never end.

You can see now why some people recommend to avoid using while loops as they have the possibility to result in an endless loop. The result is a dead lock, a state that can’t ever be left.

Also you can see, why the while loop is less obvious as it requires implicitly some additional elements that are not explicitly required by the syntax such as a way to end the loop if necessary and possibly some way of keeping track of the number of iterations. For a better understanding, you can recreate the functionality of a simple for loop as well:

iterator = 0
end_value = 5
while (iterator < end_value):
    print("Execute code here several times!")
    iterator = iterator + 1    # change the number of iterations

The code snippet above shows how you can recreate a for loop manually. Sometimes, this gives you more control how the loop should react. Most of the time, though, you will not use while loops with a counter, rather you will use it with some kind of check to compare boolean values, string values or number values which will change the loop condition so the loop will finish. For example when a button is pressed, an electro-mechanical state of a sensor has changed or if the user has given a certain input.

The following example will ask the user to input his password and then check if it is correct. It will do it an infinite amount of time as long as the input that has been given is incorrect:

password_is_correct = False
password = ""
while (password_is_correct == False):
    password = input("Please enter the correct password! ")
    if (password == "123456"):
        password_is_correct = True
    else:
        password_is_correct = False
        print("Wrong password: Access Denied! Try again!")
print("Hurray, the password was correct!")

Sometimes, an infinite while loop is exactly what you want. This is rather common for the main program of a piece of software as it should not just stop but keep going forever. This is generally true for robotic systems that often use while loops to describe their main program and then run forever until they are shut down or run into an error. In this case, shutting down the loop means to change its input condition to false. However, there is another way to leave a loop without changing its input condition: the break keyword.

Breaking a loop

The break keyword can be used to exit the loop immediately. This means that the loop will not reach its end but it will exit at the spot where the interpreter encounters the break statement. Leaving the loop with a break is usually done in combination with a conditional statement.

Here is an example on how to use the break statement:

password_is_correct = False
password = ""
counter_trials = 0
while (password_is_correct == False):
    password = input("Please enter the correct password! ")
    if (password == "123456"):
        password_is_correct = True
    else:
        password_is_correct = False
        counter_trials += 1
        print("Wrong password: Access Denied! Try again!")
    if counter_trials >= 3:
        print("Maximum of trials reached, locking the device!")
        break
    print("End of this loop has been reached successfully!")

The example above shows a simple algorithm that asks for a password by using a while loop, just like in an example before. In addition to that, there is a condition that the password may not be more than three times incorrect. In this case, the loop will exit through the break statement. This simple case could also have been resolved by simply changing the variable “password_is_correct” to True, but this would have three major consequences:

  1. The variable “password_is_correct” would have a value that does not match the situation.
  2. The program would need to run code (here the input condition validation) even though this is not necessary.
  3. The rest of this loop would still be executed, even though this might not have been the intention.

When to use a break often depends on the intentions of the program and how the loop should be exited. Often, there are several possibilities to obtain the same result.

There is also a way to skip parts of the loop, this is done with the continue statement.

Continue

In some cases, you don’t want the loop to be finished at a certain point, but you also don’t want it to go through the rest of the code inside the loop. A break would be interesting to use but nit quite do the job in this case. The continue statement will make the loop skip the remaining part of the code and then continue in the next iteration.

Consider the following example where the loop simply goes through numbers 0-19 (20 is excluded) and prints the odd numbers and skips the even numbers.

for counter in range(20):
    if (counter%2==0):
        continue # skip even numbers and continue loop
    print(counter) # will not be printed if counter is even

The example above will continue with the next loop iteration after it reaches the continue statement, this means that the print statement will not be executed.

Loops are for many applications very useful, especially when you need to repeat code several times. While loops are especially useful when you want to repeat an action for an undefined amount of times, for example when the exact number of iterations is not known yet, or if there is no fixed number of iterations. Loops are a critical element for robotic applications too. When a robot needs to move forwards until it approaches a wall in front, the while loop condition will be based on the state of a sensor of the robot. There are many more examples, different for each situation.

Another interesting way to avoid the repetition of code is the use of programming functions.

Continue learning about functions or go back to revisit conditional statements.