Why Loops in Python Are Needed in Program Coding
In all programs, a code block needs to be executed many times. Loops in python give our program the capability to repeat a code block using for loop and while loop.
A brute-force way to repeat the section of the code is to write the same block of code as many times as the program application requires. Typing the same code several times is a lot of work. Besides, it is tedious.
Looping a block of code to execute it many times is an essential requirement in all programs.
There are two types of loops.
- The for loop lets us execute a block of code a fixed number of times.
- The while loop, on the other hand, executes the block of code and keeps on repeating that block until an event happens.
On the Flow Control page, we wrote several programs that use the if, if-else, and else-if statements for program flow control.
On this page, we will write a few flow control programs that incorporate both loops and if, if-else, and else-if test conditions.
Loops combined with if, if-else, and else-if test conditions make programming very efficient and elegant.
Information on for
loop, while
loops, and if, if-else, and else-if statements is at the link here.
Loops in Python – the Problem Description
Generally, most programs have situations where the program needs to execute a block of code several times.
Michael ran into this situation when he celebrated his 8th birthday.
He invited 30 friends, who brought gifts.
Michael decided to send ‘Thank you’ notes to his 30 friends.
Michael got very bored after writing about five ‘Thank you’ notes.
Let us see how Python would write ‘Thank you’ five times. The following code will output ‘Thank you’ five times.
>>> print(‘Thank you’)
>>> print(‘Thank you’)
>>> print(‘Thank you’)
>>> print(‘Thank you’)
>>> print(‘Thank you’)
If Michael wants to write 30 ‘Thank you’ notes, he will need to repeat the print(‘Thank you’) statement 30 times.
This is a lot of typing, is very tedious, and is not a good use of time. It would be nice to be able to do this task a little easier.
Python programming language has two LOOP instructions that allow us to execute a block of code repeatedly. The two LOOP instructions are:
- for- loop
- while loop
for Loop
We discussed for
statement in detail in Python Functions 1 page. The following is a recap.
for
loop statement will repeat a statement (or a block of code) a number of times as specified in the range()
function. The following is the syntax of for
statement:
>>>for
x in
range (0, n):
Block of code goes here
Where ‘x’ is the label of the variable that counts the loop number. It is called the counting variable.
range() Function
range()
specifies the number of times you want the for
loop to repeat the block of code following the colon. For reference, the range()
function was discussed in Python Functions 1 chapter.
range(0,n)
statement tells Python to start at loop count x = 0, execute the block of code that follows the colon, then loop back to the top (for-range statement).
On the second iteration of the loop, the counting variable x is incremented by 1. The program executes the block of code with counting variable x = 1 again.
After the second loop, the program loops back to the top, increments the counting variable x to 2 and executes the block of code again.
The execution of the block of code continues until it has executed the code corresponding to x = n-1. The loop stops just before x = n.
Thus, the number of times the block of code is repeated is n.
Note: ‘in’ and ‘for
‘ are keywords. Keywords are explained in Appendix. These are the words that you cannot use as your own defined variables.
Also, notice the colon (:) at the end of for
statement. This colon is required by the syntax of the for
statement.
Getting back to Michael’s problem, the following is how Python will write ‘Thank you’ five times using the for
loop. He does not have to type a lot of text using the for
loop.
PROGRAM EXAMPLE: for-range() LOOP TO WRITE FIVE THANK YOU NOTES
>>> for x in range(0,5):
print('Thanks for making my birthday very special')
Thanks for making my birthday very special
Thanks for making my birthday very special
Thanks for making my birthday very special
Thanks for making my birthday very special
Thanks for making my birthday very special
>>>
This is neat. Just one line of code solves Michael’s problem. If Michael wanted to print 30 ‘Thank you’ notes, all he has to do the change the range function from range(0,5)
to range(0,30)
.
for Loop with Range() Function and List Data Type Using Indexing
The above program is good since it saves a lot of typing, but would it not be nice to make the ‘Thank you’ notes personal?
You can customize the ‘Thank you’ notes by combining the for
loop with the list
data type we discussed in the Python Data Types chapter.
First, you will define a list
data type variable and type the names of all the friends in the list. This is shown in the statement below.
>>> friends = [‘Robert’, ‘Steve’, ‘Tricia’, ‘Alice’, ‘David’]
In the previous example, we used a range from 0 to 5. In this program, we will use range to loop from index[0] to index[5] in the list called ‘friends’.
PROGRAM EXAMPLE: for-range LOOP WITH LIST DATA TYPE USING INDEX
>>> friends = ['Robert', 'Steve', 'Tricia', 'Alice', 'David']
>>> for x in range(0,5):
print(friends[x], ': Thanks for making my birthday very special!')
Robert : Thanks for making my birthday very special!
Steve : Thanks for making my birthday very special!
Tricia : Thanks for making my birthday very special!
Alice : Thanks for making my birthday very special!
David : Thanks for making my birthday very special!
>>>
If Michael wants to send the ‘Thanks note’ to 30 friends, all he has to do is define a list of 30 names. Then, the print function will loop through all 30 indices to print the ‘Thank you’ notes.