4.2 Loops and Iterations
Iteration is the repeated execution of the same block of
code.
Why do we keep doing the same thing? Assume we want to enter
marks for a student and determine if the student passed the exam with more than
50 points. For each pupil, we would write one line of code. Let's imagine we
have five pupils and wish to accomplish the same thing. One method is to
duplicate the code developed for one student five times.
Is this the best approach? If we could write the code once
and then repeat it five times. It would be easy to write, and if required,
switching languages would allow us to execute code repeatedly.
We already know how to develop code for inclusion.
Let's take a closer look at how this works. We have a list
of 5 grades and want to publish the grades. We begin with student 1, or item 0
on the list. We need to continue or iterate this for all five pupils, therefore
we look to see if the student is under the age of five. The print statement is
then executed. Also, we must ensure that the student number is increased by one
so that the next student on the list may be taken.
Considering the nature of iterations, these can be
categorized as,
- Definite iteration, in which the number of repetitions is specified explicitly in advance
- Indefinite iteration, in which the code block executes until some condition is met
In Python, indefinite iteration is performed with a while
loop, and definite iteration is implemented with for loops.
The for Loop
The block of code is repeated or iterated a certain number
of times in the for loop. The format or syntax of the code is to have the for
Keyword and specify that for each iterating variable in the sequence, the code
must be looped through.
for iterating_var in sequence:
statements(s)
The two keywords are "for" and "in". We
define variables such as the iterating variable and the sequence. The sequence
can be a list of numbers, with the iterating variable taking an item from the
beginning of the list until it reaches the end. There is also a colon. Don't
forget the colon; omitting it will result in a syntactic mistake.
The loop body is the repeating set of sentences. The loop body
must be indented to the right in order for the computer to recognize that the
block of code belongs to this loop.
for counter in [1,2,3,4,5]:
print("This
is a loop: counter = ", counter)
Range
Function
It may not be practical for us to type the sequence of items
that we want the iterating variable to take. So we have the range function to create
the sequence of numbers we want.
One way of indicating the range function is to input when to
stop the sequence. So if we input 10, the sequence will have 10 numbers from 0
to 9. The sequence ends at 9 because 0 is counted as an item in the sequence.
range(stop)
example:
list(range(10))
output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
If we do not want start from 0 we can indicate where we want
to start the sequence. In this example we want the start variable to be 5 and
the stop variable to be 10. Note that the list will go from 5 to 9. Let's
create a range less than 10.
range(start,stop)
example:
list(range(5, 10))
output:
[5, 6, 7, 8, 9]
If you do not want to increment by 1 then you can indicate
how you want to step or increment each item.
range(start,stop,step)
example:
list(range(0, 10, 3))
Output:
[0, 3, 6, 9]
First, we'll set the total to 0 so that there's nothing in
there. The for loop is then used to run over all of the numbers. To begin, we
require an iterating variable that changes with each iteration. Counters are
used for this. Then we must construct a sequence of even numbers. The range
function comes in handy here, since we start at 0, halt at 101, and step
through in 2. The counter must then be added to the current total. Take note
that on this line of code, the old value of total and the counter on the right
hand side will be passed to the left hand side total and utilized in the
following step.
Play with the code and see if you can adapt the example to
add all the odd integers between 0 and 100. or even numbers between 100 and
200, and so on. The more you attempt, the more you will learn. It is difficult
to learn Python through reading. You should try your hand at coding!
total = 0
for counter in range(0,101,2):
total = total +
counter
print('total = '),
print(total)
The basic syntax of the Python while loop is,
while <condition>:
<statement(s)>
As with other Python control structures, the line/set of
lines to be performed as the loop body is specified here with the imperative
indentation. The loop-controlling condition is the condition. It must be
declared and given an initial value before the while loop can begin. To keep
the loop going, its value is changed within the loop body. When the loop
stratifies, the is evaluated as a Boolean expression, which is either true or
false. If the condition is true, the loop body is run. If it is determined to
be false, the loop will not be run. As previously stated, the loop controlling
variable in the expr> is changed frequently throughout the loop.
num = 5
while (num !=0) :
print ('Hello
World!')
num = num - 1
Output will be
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
This is how it will be done. First, we set num to 5. Then it
will verify the condition and proceed to execute the loop body if it is true.
It will lower the number by one at each iteration until it reaches zero, at
which point it will exit the loop and complete the code.
Break and
Continue statements
Python allows terminating the iteration of the loop
prematurely with the break and continue keywords.
The loop can be halted completely by using the break
command. When a break statement is encountered within the loop, the loop is
exited and program execution is handed to the first statement after the loop
body.
With the continue statement, the current loop iteration is
immediately terminated. This statement skips the rest of the loop statement and
starts the next iteration of the loop.
In while loops,
In for
loops
break and continue working the same way with for loops as
with while loops. Break terminates the loop completely and proceeds to the
first statement following the loop, and continue terminates the current
iteration and proceeds to the next iteration.
Python allows to use an ‘else’ clause with loops:
·
If the "else" clause is used with a
for loop, the "else" clause is executed when the loop has finished
iterating the sequence given.
·
If the "else" clause is used with a
while loop, the "else" clause is executed when the loop condition
becomes false.
Take a look at the example code. With an otherwise clause,
the loop in this example will be performed until it encounters the number 5. If
it discovers number 5, it will break and report "number found" before
exiting the loop. If number 5 is not discovered, the loop will be completed,
and the else clause will be invoked to indicate that the number was not found.
Selecting the Loop
·
The "for" loop is generally used when
the number of iterations or the sequence can be identified at program
compilation or before execution of the loop.
·
The ‘while’ loop can be used for any other
situations.
Nested Loops
Nested loops
are also possible. To create a nested loop, we may nest a loop within another
loop. The syntax is as follows, with the loop indented within the out loop.
When we execute for each iteration of the outer loop, we iterate over the whole
inner loop. When it is done, it will return to the inner loop, take the next
iterating variable from the outer loop, and repeat the inner loop iteration.
Nesting is the process of putting one loop inside another. We can have as many
loops as we want within a loop. We may have a loop inside a loop inside another
loop, for example. It should be noted that if each loop is lengthy, it will
take a while.
When
stacking loops, we may also have different combinations. For and while, as in
the previous example, or while and for, as in this example, or even while and a
while or for and a for loop. Any number of nesting layers and any number of
loop combinations are conceivable.
A nested
loop is seen below. Looking at the example, we may consider printing one line
of characters using a for loop that ranges from 0 to 9. We'd want to have all
five lines now. So we added another loop outside of this one to iterate from 0
to 4 five times. This will generate 5 lines of text.
The pass
Keyword
Although
pass has no effect on loop execution, it can be used to do nothing in a loop.
We cannot have an empty piece of code within a loop. As a result, we can
utilize the pass to create some code that includes a loop that accomplishes
nothing.
We have a list
of fruits in this example. We don't sure what to do with them right now, but we
want to construct a loop so that we don't forget to do anything with the fruits
later. A syntax error will be generated if we write the code without any
executable code for the loop body other than the remark.
We may avoid
this by including a pass statement within the loop. When we know what to do
with the fruits inside the loop, we can eliminate the pass and replace it with
some code.










0 Comments