Which Type of Loop is Best?
So, now you know the two types of loops in Python: while and for. One is not better than the other, but the type of loop you choose should match the type of problem you need to solve.
-
- The for loop is best when we know, before the loop executes, precisely how many repetitions we need.
- The while loop is best when we do not know how many times the loop will need to repeat, and where the loop may not execute at all if the condition is False initially. In other words, the body of the loop may be repeated 0 or more times.
Augmented Assignment Operators
Simple assignment statements like these are quite common in programming: In all cases, you’ll notice that the variable on the left of the assignment operator (=) also appears in the expression on the right. For convenience, Python supports a special set of short-hand operators designed for this situation called augmented assignment operators. Augmented assignment operators combine the assignment and arithmetic operations so that you don’t need to type the variable name twice. The examples above can be rewritten as:
You may find this notation strange at first, but as you gain more experience you’ll naturally start to use it more and more. If you know a little Java or C/C++, you might have seen the ++ and — operators. These operators do not exist in Python.
Sentinels
As mentioned above, a while loop is usually used in situations where we don’t know exactly how many times a loop will need to iterate. The number of repetitions might depend on how many data values a user enters, for example.
In situations like this, we need to have a way to know that the user wants to stop entering values and terminate the loop. To do this we use what is called a sentinel value. A sentinel value is a special value that marks the end of a data sequence.
1 2 3 4 5 6 7 8 9 |
total_marks = 0 mark = int(input("Enter A Mark (or -1 to end): ")) while mark != -1: total_marks += mark # Rather than: total_marks = total_marks + mark mark = int(input("Enter A Mark (or -1 to end): ")) print("The sum of the marks entered is:", total_marks) |
In this example, -1 is used as a sentinel value to tell the while loop when to terminate. A sentinel value must be distinctive enough that it will not be mistaken as a regular data value. Here I’ve used -1 since a mark will never be negative.
Input Validation
Another very common application of condition-controlled loops is to check that data entered by the user is valid before it is used in the computation. This process is called input validation.
1 2 3 4 5 6 7 |
mark = int(input("Enter A Mark: ")) while (mark < 0) or (mark > 100): print("Sorry, the mark must be within the range 0 and 100.") mark = int(input("Enter A Mark: ")) print("The mark accepted was", mark) |
There is a famous saying in computer science: “Garbage In, Garbage Out” (or GIGO). In other words, the integrity of a program’s output is only as good as the integrity of its input. For this reason, you should always design your programs such that bad input is never accepted.
Nested Loops
Just as we can have nested decision structures, we can also have nested repetition structures. A loop that is inside another loop is called a nested loop. Here’s an example that will display a triangle on the screen:
1 2 3 4 5 6 |
# This nested loop displays a triangle of "*" characters # 5 rows high, and from 1 to 5 columns wide. for row in range(1,6): for col in range(row): print("*", end="") print() |
The inner loop goes through all of its iterations for every single iteration of the outer loop. The example above also demonstrates Style Rule #2: Code Commenting. When you have (tricky) code that may not be obvious what it does at first glance, one should include a 1 or 2 line comment explaining it.
Trace Tables
The nested loop example is very short, but may be hard to get your head around. To help analyse code like this we can use a paper and pencil technique called a trace table. Normally a trace table includes a column for each variable and a column to describe any output. Here is a trace table for the previous example:
Yes, this can be tedious, but often (e.g., in a test situation) there’s no better way to analyse what a particular fragment of code is doing.
You Try!
-
- Start a new page in your Learning Journal titled “2-5 More On Loops“. Carefully read the notes above and in your own words summarize the key ideas from each section.