By the end of this lesson, you should be able to:
In this lesson we will study while loops, which are more intuitive in many applications. Let's take a look in the following recipe application.
You can see, steps 3 and 4 are repeated three times. We also kept a note of the count to make sure that we do not put in less or more than the recipe. In some loops we may not use a counter, and instead repeatedly perform some steps until a condition is met.
Consider the following steps from a recipe:
We will be looping between step 3 and steps a and b until bubbles appear in the mixture. Appearance of bubbles is a condition that will terminate the loop and take us to step 4 and onwards.
When we execute a set of computer instructions repeatedly, we put them in a loop rather than writing them over and over again.
In this lesson, we will discuss while loops. We will start by briefly discussing the need for repetition structures in programming languages. After that, we will go over the syntax of the while loop and also discuss the loop variable, loop body and loop expression. In the next section, we will cover break and continue statements. At the end of the lesson, we will go over nested loops.
The module concludes with a comparison between for
and while
loops, highlighting scenarios where it is better to use each statement.
The concept of iterative statements is both useful and applies to many real-life scenarios. By completing this lesson, you should build rigorous understanding of the concept. As a general recommendation to those studying loops for the first time, it is good to have a paper and pencil to trace loops as you study them. As you progress in your learning, you will notice that you gradually divert from using the paper and pen as you become more confident with loops. Also, watch out for infinite loops because they will come after you at any instance you are less careful in your design.
Modern processors can perform calculations at a phenomenal speed. Repetition structures allow programmers to leverage the immense processing power of the computers. The following two examples establish the need of loops in programming languages:
Imagine the program running in a control room that monitors the temperature of a room where medicine is stored. The program has to run constantly and check for temperature periodically. It will raise an alarm if the temperature in the room rises above a given threshold.
The code to pull the current temperature from the sensor and to determine if the alarm needs to be raised has to run in a loop. Figure shows the flow chart of the program.
We will need to perform a lot of calculations to find if 5179 is a prime number or not. If we use loops to perform these computations, our code will be very short, and it will also be dynamic. Theoretically, the same code can be used to check any number and determine if it is a prime number or not.
In the next section we will use the syntax of Python programming language to program while loops.
while
Loops
One of the most important parts of the loop is the logic that is used to determine when the loop will terminate. Programmers mostly use two methods to set up the loop termination condition. One, using a loop variable, and two, using sentinel value.
Prog 7-01 shown in Code Listing demonstrates the use of loop variable in a while loop. The program assigns to the variable named counter. The value of counter is incremented inside the loop body (Lines 8 and 9), and the condition on line 7 checks is the value of counter is less than or equal to 3.
# Program Name: Prog 7-01
# This program is part of Lesson 07 of the course
def main ():
counter = 1
print("Loop beginning")
while counter <= 3:
print(f"Current Counter value {counter:d}")
counter += 1
print("Loop ended")
main()
Let's go over the code line by line from lines 5 to 11.
Line 5 | Loop variable named counter is assigned a value of 1 |
Line 6 | Loop beginning is printed on the console |
Line 7 | This line is the loop header. It starts with the
keyword while, which tells the Python
Interpreter that a while loop is starting. Right after the keyword is a
test expression containing a relational operator. We
already know from the lesson 5 (conditional statements) that relational
operators result in either True or False.
The loop body (Lines 8 and 9) will execute repeatedly as
long as this test expression remains True.
A colon at the end of the expression denotes the end of the loop
header. Test Expression: The value of counter at this point of execution is 1. The expression is testing if the value of counter is less than or equal to 3. This will result in True and that is why the first line in the loop body (line 8) will be executed next. Note: All indented lines of code under the loop header are part of the loop body. |
Line 8 | This statement is part of the loop body. It prints the value of the variable counter on the console. |
Line 9 | This statement is also part of the loop body. The current value of counter, i.e. 1, moves up by an increment of 1 and becomes 2. |
Lines 7 | At the end of the loop body, the execution returns to the loop header. The test expression is rechecked, and this time the value of counter is 2. The expression again returns True (2 <= 3) and therefore the loop body will execute again. |
Lines 8 and 9 | The current value of the counter (2) is printed and the value is again incremented by 1. The new value of the counter is 3. |
Line 7 | The execution returns to the loop header, and the expression (3 <= 3) is still True, so the loop body will execute again. |
Lines 8, 9 | 3 is printed on the console, and the value of counter is incremented by 1 and becomes 4. |
Line 7 | The Test expression executes again, but this time the value of the counter is 4. As 4 is not less than or equal to 3, the expression returns False. The loop body will be skipped, and the execution will jump to line 11. |
Line 11 | The Loop ended is printed on the console. |
One full execution of the loop body is called iteration. The loop in Prog 7-01 iterates three times, but the loop header is executed 4 times.
The output of Prog 7-01 is shown below in Console 1:
Loop beginning
Current Counter value 1
Current Counter value 2
Current Counter value 3
Loop ended
Some questions are included below for you to self-evaluate your understanding. Please consider your answer before revealing the answer below.
In this second example of the lesson we will use a sentinel value to terminate the loop. But, before continuing we will briefly discuss Arithmetic series.
An arithmetic series is a sequence of numbers that has a starting number and a constant difference. The series begins from the starting number and maintains a constant difference between successive terms. For example, if an arithmetic series has a starting value of 5 with a constant difference of 4, the sequence will be:
5, 9, 13, 17, 21, 25, . . .
Prog 7-02 prints an arithmetic series for a user provided starting value and difference. We will use a loop to print the terms and a sentinel value to terminate the loop. Code Listing shows the source code for the program.
# Program Name: Prog 7-02
# This program is part of Lesson 07 of the course
def main ():
series_number = int(input("Enter the starting number: "))
difference = int(input("Enter constant difference: "))
print()
print("Printing Arithmetic Series")
print(f"{series_number:d}")
print_next = input("Do you want to print next number (Y/N): ")
while (print_next == 'Y' or print_next == 'y'):
series_number += difference
print(f"{series_number:d}")
print_next = input("Do you want to print next number (Y/N): ")
print ("\nProgram Terminating")
1 main()
Let's go through the code line by line:
Lines 5, 6 | Takes user input for the starting value of the series and the constant difference between terms. Both input values are type casted to integers. |
Lines 7, 8 | A blank line and Printing Arithmetic Series is printed on the console. |
Line 9 | Prints the first term of the series on the console. The first term is the same as the value assigned to the variable series_number. |
Line 11 | The user is prompted to provide a sentinel value. The user can type in anything, but the next value will only be displayed if the user enters either a capital or a small letter 'y'. |
Line 13 | Test expression compares the user entered string (in line 11) against 'y' or 'Y'. The expression will return False for any other input. We assume the user entered 'y'. |
Lines 14, 15 | The variable series_number is incremented by the value assigned to the variable difference. The new value of series_number is printed on the console. |
Line 16 | The user input is taken inside the loop body to determine if the user wants to continue iterating the loop. We assume the user enters 'y' again. |
Line 13 | The Test expression is executed again. The expression returns True, and therefore the loop body will be executed next. |
Lines 14, 15 | The value of the series_number is incremented by the value of the difference and then printed. |
Line 16 | The user input is again taken. We assume the user enters a value other than 'y' or 'Y'. print_next is assigned the new value and the test expression will be executed next. |
Line 13 | This time the expression returns False and the execution will jump to line 18. |
Line 18 | Program Terminating is printed on the console. |
A sample run of Prog 7-02 is shown in Console 2.
Enter the starting number: 5
Enter constant difference: 4
Printing Arithmetic Series
5
Do you want to print next number (Y/N): y
9
Do you want to print next number (Y/N): y
13
Do you want to print next number (Y/N): y
17
Do you want to print next number (Y/N): y
21
Do you want to print next number (Y/N): y
25
Do you want to print next number (Y/N): y
29
Do you want to print next number (Y/N): n
Program Terminating
In this sub section we will take a problem and solve it using loops. The problem statement is given below:
Write a program to display the Fibonacci series on the console. As Fibonacci series is an infinite series, ask the user to enter the number of terms she wants to display for the series. Display all the terms of the series in a single line, separated by commas. The Fibonacci series is explained below:
Fibonacci series starts at zero and the second term in the sequence is 1. After the first two, every term is the sum of the previous two terms in the sequence. The series proceeds as follows:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, . . .
As an example, consider the term 8. It is calculated by adding the previous two terms, i.e. 5 and 3. Similarly 34 is computed by adding 13 and 21.
Before proceeding, we encourage you to write down the steps needed to solve the above problem. You do not need to write the Python code as yet. You can simply write English sentences to describe the steps, and the logic required to solve this problem. Generally, it is better to take some time to understand the problem and to think about the approach you will take to solve it, before you start writing the code. For example, the first step can be: Take input from the user to specify the number of terms to display.
Step 1: Take input from the user to specify the number of terms to display
Step 2: Display the first two terms of the series, i.e. 0 and 1
Step 3: Create a loop variable, and set it to 2.
Step 4: Initiate a while loop that runs until the loop variable is equal to the number of terms we need to print.
Step 4.1: Calculate the next term by adding the previous two terms.
Step 4.2: Increment the loop variable.
Note: All the terms of the Fibonacci series must be printed on a single line. Also the previous two terms need to be stored for the calculation of the next term.
The Python code to display Fibonacci series according to the requirements set forth in the problem statement is given in Code Listing 3 (Prog 7-03 ).
# Program Name: Prog 7-03
# This program is part of Lesson 07 of the course
def main ():
no_terms = int(input("Enter the number of terms: "))
print ("Printing Fibonacci Series")
fib_number = 0
print(f"{fib_number:d}", end = ',')
fib_number = 1
print(f"{fib_number:3d}", end = ',')
prev_term_1 = 0
prev_term_2 = 1
counter = 2
while (counter < no_terms):
fib_number = prev_term_1 + prev_term_2
print(f"{fib_number:3d}", end = ',')
prev_term_1 = prev_term_2
prev_term_2 = fib_number
counter += 1
print()
print("\nProgram Terminating")
main()
Before going through the code, we will first discuss a new
functionality of the print
function, which is
introduced in Prog 7-03.
The default behaviour of the print
function is that
a new line is started in the console after it ends. The
following two lines of code will display My and
name on two different lines.
print("My")
print("name")
But we can override this default behaviour of the print
function through the use of the end parameter.
The following two lines of code will print My
and name in a single line of console although
they are in separate print
functions.
print("My", end = ' ')
print("name")
This is because the default behaviour for the first print
function was changed by the use of end = ' '.
Rather than starting a new line after it ends, it will only
place a space. Note: There is a space between the
single quotes.
Let's go through the source code of Prog 7-03 and iterate the while loop thrice.
Line 5 | The user enters a number to specify the number of Fibonacci terms to be displayed by the program |
Line 6 | Printing Fibonacci Series is printed on the console. |
Lines 7, 8 | The first term in the Fibonacci series, which is
zero, is assigned to the variable fib_number.
fib_number is then printed on the console, but a new line
is not started after printing, rather a comma is displayed
after the value. Note: The first term is 0 |
Lines 9, 10 | The second term of the series is now assigned to the
variable fib_number. The value of fib_namber
is now 1. It is also printed on the console in the same line
as the previous print call, and a comma is
displayed after the value without starting a new line in the
console.
|
Lines 12 - 14 | Three new variables are created. prev_term_1
and prev_term_2 will be used to store the
last two terms in the series. counter is a
loop variable which will be incremented in
the loop body. It is set to 2, as we have
already displayed two terms of the Fibonacci series. The current values of the variables are:
|
Line 16 | The While loop starts executing. The test expression is used to limit the number of terms displayed to be equal to the user specified value (no_terms). |
Lines 17, 18 | The third term of the Fibonacci series is calculated
by adding the first and the second term (0 + = 1). The
values of the first and the second terms are assigned to prev_term_1
and prev_term_2. The third term is printed
on the console without creating a new line. The current values of the variables are:
|
Lines 19, 20 | As we calculated the third term in the previous line
of code, therefore the previous two terms are now second and
third instead of first and second. These terms will be
required to calculate the fourth term. prev_term_1
takes the value of prev_term_2 and prev_term_2
is assigned the value of fib_number. The current values of the variables are:
|
Line 21 | The counter is incremented by 1 and it becomes 3 |
Line 16 | The test expression is checked again and we assume it is still True. |
Lines 17, 18 | The fourth term is calculated. Its value is 2 (1 + 1
= 2). The value is printed on the console. The current values of the variables are:
|
Lines 19, 20 | prev_term_1 takes the value of
prev_term_2 and prev_term_2 is assigned
the value of fib_number. The current values of the variables are:
|
Line 21 | The counter is incremented and becomes 4. |
Line 16 | The test expression is evaluated again and we assume it is still True. |
Lines 17, 18 | The fifth term is calculated. Its value is 3 (1 + 2 =
3). The value is printed on the console. The current values of the variables are:
|
Lines 19, 20 | The prev_term_1 takes the value of
prev_term_2 and prev_term_2 is assigned
the value of fib_number. The current values of the variables are:
|
Line 21 | The counter is incremented and becomes 4. |
Line 16 | We assume that the test expression returns False this time and the execution jumps to line 23 |
Lines 23, 24 | An empty line and Program Terminating is printed on the console. |
A sample run of the program is shown below in Console 3.
Enter the number of terms: 12
Printing Fibonacci Series
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,
Program Terminating
While loops can be error prone for new programmers. Apart from syntax errors, new programmers often encounter logical errors while coding loops. Initially it takes time to debug loops, but with practice you will soon be able to quickly find bugs.
Consider your answers for Snippets 7-12, then click on the Answer button to check your work.
Snippet | Space for your answer |
---|---|
Snippet 7:
|
|
Snippet 8:
|
|
Snippet 9:
|
|
Snippet 10:
|
|
Snippet 11:
|
|
Snippet 12:
|
Snippet | Answers |
---|---|
Snippet 7:
|
Code Explanation: The loop does not iterate at all. The value of the count cannot be 5 and not 5 at the same time. Note: Expressions on both sides of the and (Boolean operator) must be True for the loop body to execute. |
Snippet 8:
|
Code Explanation:
The Boolean value of the flag is initialized as True. The expression not not flag results in True as well. Therefore, the loop is iterated once, but the value of the flag is changed to False in the loop body. The second iteration does not occur and the iteration is printed just once. |
Snippet 9:
|
Code Explanation: This is a case of an infinite loop. At least one of the expressions on either side of or (Boolean operator) needs to be True for the loop body to execute. As the flag is initially True, the loop will execute. The value of the flag becomes False in the loop body. The test expression still returns True as not flag results in a True. |
Snippet 10:
|
Code Explanation:
This is an infinite loop as well. In Python, every number is treated as True except zero. |
Snippet 11:
|
Code Explanation:
The loop body will never execute as zero will be treated as False. |
Snippet 12:
|
Code Explanation:
This is an infinite loop as well. |
while
A nested loop is a loop inside a loop. The previous sentence may seem a bit overwhelming to new programmers, at least it did to me years ago, but trust me, it is not that hard to understand.
The inner loop iterates fully for each iteration of the outer loop. Consider drawing the following asterisks (*) on a piece of paper.
* * * * *
* * * * *
* * * * *
* * * * *
We want to draw 5 asterisks on each of the 4 lines. We will place the pencil at the start of the first line and draw 5 asterisks. Then, shift the pencil one line down to the start of the second line and draw 5 asterisks and so on.
The outer loop handles the placement of the pencil at the start of the successive lines once 5 asterisks have been drawn. The inner loop is responsible for drawing 5 asterisks in a single line. The inner loop iterates 5 times for each iteration of the outer loop to draw 5 asterisks.
Prog 7-06 in Code Listing 6 shows code for the above mentioned program.
# Program Name: Prog 7-06
# This program is part of Lesson 07 of the course
def main ():
row = 1
while row <= 4:
col = 1
while col <= 5:
print("*", end='')
col += 1
print()
row += 1
main()
Line by line code description is given below:
Line 5 | The variable row is assigned the value 1. It is the loop variable for the outer loop. |
Line 6 | The loop iterates four times. The value of the row will be 1, 2, 3, and 4 for each successive iteration. |
Line 11 | Line 11 is part of the outer loop. It is not included in the
inner loop. print is used to change the line when 5
asterisks have been drawn on a line by the inner loop.
|
Line 12 | Line 12 is also part of the outer loop only, and it increments the value of the row. |
Line 7 | Line 7 is also part of the outer loop only. It assigns 1 to the loop variable of the inner loop called col. Remember that for each new line the pencil needs to be shifted to the start of the line. We are resetting the loop variable of the inner loop so that it starts iterating from the beginning. |
Line 8 | The inner loop iterates 5 times. |
Line 9 | For each iteration of the inner loop, an asterisk is drawn without starting a new line. |
Line 10 | The value of col is incremented. |
Each time the inner loop has fully iterated and 5 asterisks have been drawn, the following steps are taken by the code:
In the next example, we will go through another program with nested loops. This is a little longer example, and it incorporates different concepts that you have learned up until now in this course. Code Listing 7 shows the code for Prog 7-07 .
# Program Name: Prog 7-07
# This program is part of Lesson 07 of the course
def draw_triangle(lines):
countV = 1
while countV <= lines:
countH = 1
while countH <= countV:
print("*", end='')
countH += 1
countV += 1
print()
return "Triangle displayed"
1 def draw_square(lines):
countV = 1
while countV <= lines:
countH = 1
while countH <= lines:
print("*", end='')
countH += 1
countV += 1
print()
return "Square displayed"
2 def main ():
choice = input("What do you want to draw (T/S): ")
30. lines = int(input("Enter size: "))
3
3 msg = "Incorrect choice"
3 if (choice == 'T' or choice == 't'):
3 msg = draw_triangle(lines)
3 elif (choice == 'S' or choice == 's'):
3 msg = draw_square(lines)
3
3 print(msg)
3 main()
Let's go through the function draw_triangle first.
Line 4 | A function takes an integer parameter named lines to start execution. |
Line 5 | The loop variable for the outer loop named countV (V stands for vertical or rows) is assigned a value of 1. |
Line 6 | In the last example, the number of rows were fixed to 4. In this example, the number of rows or the height of the triangle is equal to the value passed as parameter (lines) to the function. |
Line 7 | The loop variable for the inner loop is assigned 1. |
Line 8 | The number of times the inner loop iterates depends on the
current value of countV. For the:
|
Lines 9, 10 | Prints an asterisk without starting a new line and increments countH. |
Line 11 | countV is incremented by 1. |
Line 12 | A new line for printing is started. |
Line 14 | Triangle displayed is returned as a string to the calling function. |
Please go over the function draw_square and find out its functionality. It is quite similar to the Prog 7-06.
The main function takes two inputs from the user. The first input is the choice between drawing a triangle or a square. The user entered option is assigned to the variable choice. The second input is the size of the triangle or square, and is assigned to the variable lines after type casting it to an integer.
A draw_triangle is called if the user's choice was either a capital or small t. A draw_square is called in case user entered capital or small s.
Two sample runs of Prog 7-07 are shown in Console 6 and Console 7.
What do you want to draw (T/S): T
Enter size: 7
*
**
***
****
*****
******
*******
Triangle displayed
What do you want to draw (T/S): s
Enter size: 6
******
******
******
******
******
******
Square displayed
while
vs for
After learning for loops and while loops, we want to highlight the
relationship between the while
and for
loop
statements. Both are considered iterative statements, and the only two
iterative commands in Python.
The two commands are interchangeable. This means any program written using
a for
statement can be translated to a while
loop and vice versa. To understand why this is the case, we need to break
down the steps involved in any loop.
For any iterative statement to work, the following steps need to be implemented:
If any of the above is absent, then the loop cannot function as expected. With the absence of the incrementing step, the function can get stuck in an infinite loop. This could also happen if the condition is poorly designed.
In a while
loop, the three steps are explicit. However, in
the for
loop, the three steps are somehow implicit. The initialization
step is picking the first element from the iterable, the condition
is to exit when there are no more elements to pick and the increment
is to pick the next item from the iterable. From this perspective, the for
statement has the advantage of needing less code. Below is the conversion
code for a 10 round iteration.
|
|
Converting from a while
loop to a for
loop is
theoretically possible for all scenarios. However, when the condition is
complex or when the condition does not involve an iterable, the process is
not straight forward. In such scenarios, the for
loop would
need to have break
statement to detect when the condition is
violated. From this perspective, the while
statement provides
better code.
Perhaps, instead of trying to evaluate which statement is better, we could
direct our attention to identifying problems that best fit each statement.
Generally speaking, if you know beforehand the number of iterations, e.g.
n
iterations, then using a for
loop is a better
candidate. Also, when you are iterating through an iterable object, the for
statement should be your first choice. For all other scenarios, the while
loop generally provides a better solution. This should explain to you why
many programmers consider the while
loop to be more generic
than the for
loop.
We started the use of loops in this lesson. Loops are a powerful feature of any programming language. We worked with the while loops and nested while loops, with a discussion on loop expression, loop body, break and continue statements.
Practice and more practice is the key to fully mastering iterative statements.
By completing this lesson, you have completed your study of the essential statements: sequential, conditional, and iterative statements. In the following lessons, the focus will be shifted to data processing which involves string manipulation, list manipulation, file manipulation, and collections. What you learned in Lessons 1 to 7 will be extensively applied in future lessons.
You could say that the course is going to be more fun from this point as the problems will be more interesting and will require more thinking.