0% found this document useful (0 votes)
15 views

Loops and Iterations

The document discusses loops and iterations in Python. It explains that loops allow code to be repeated without rewriting it multiple times. The main loop types in Python are for loops, which execute a code block a specific number of times, and while loops, which execute until a condition is met. It provides examples of using for loops with the range function and while loops to iterate through code.

Uploaded by

ravindu
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Loops and Iterations

The document discusses loops and iterations in Python. It explains that loops allow code to be repeated without rewriting it multiple times. The main loop types in Python are for loops, which execute a code block a specific number of times, and while loops, which execute until a condition is met. It provides examples of using for loops with the range function and while loops to iterate through code.

Uploaded by

ravindu
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

4.

2 Loops and Iterations


Iteration is the repeated execution of the same block of code.
Why do we need Loops and Iterations ?
Why do we repeat? Let’s say that we want to enter marks for a student and check to
see if the student has passed the exam by getting more than 50 marks. We would write
one line of code for one student. Now let’s say thea we have 5 students and we want to
do the same. One way of doing this is to copy the code written for one student 5 times.
Is this the best way of doing this? If we had a way of writing the code once yet repeat it
5 times. it would be easier to write and if necessary, change languages allow us a way
to repeatedly execute code multiple times.

We already know how to write code that goes in a sequence. We also we know how to
write code to check some condition and decide which way to go usingif-else and switch-
case in python. We can also repeat or iterate as shown in the diagram.

Let's look at how this works. We have 5 grades in a list and want to print the grades. We
start with student 1 or list item 0. We need to repeat or iterate this for all 5 students so
we check to see if the student is less than 5. Then we have the print statement to print.
And also we have to make sure that we increase the student number by 1 so that next
time we can take the next student in the list.

Considering the nature of iterations, these can be categorized as,

1. Definite iteration, in which the number of repetitions is specified explicitly in


advance
2. 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
In the for loop the block of code is repeated or iterated a specific number of times. The
format of the code or the syntax of the code is to have the for Keyword and tell that for
each iterating variable in the sequence needs to loop through the code.
for iterating_var in sequence:
statements(s)
"For" and "in" are the two keywords. The iterating variable and the sequence are
variables that we define. The sequence can be a list of numbers where each time the
iterating variable will be taking an item starting from the first one until it reaches the end
of the list. And we also have a colon. Don’t forget the colon if you forget you will get a
syntax error
The block of statements repeated is called the loop body. The lopp body needs to be
indented to the right so that the computer understands the block of code belongs to this
loop.
Let us look at an example in python. Play around with the code to see if you can add
one more iteration to the given code example.
This is a loop: counter = 6
Range Function
It may be not 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 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]
Assume that we want to write code to calculate the total of all even numbers up to 100.
First, we will set the total to need to have a place to collect the total and make it 0 so
that we do not have anything in that. Then we write the for loop to go through all the
numbers. First we need an iterating variable that would change during each iteration.
We use counter for that. Then we need to get a sequence of even numbers generated.
We get the help from range function where we start at 0, stop at 101 and step through in
2. Next we need to add the counter to the existing total. Note on this line of code the
old value of total and the counter that is in the right hand side will be given to the left
hand side total and it will be used in the next iteration of the loop. Finally after we finish
the loop, we need a print the total.
Play around the code and try to see if you can change the given code example to add
all the odd numbers beetween 0 and 100. Or the even numbers between 100 to 200,
etc. More you try your willl learn. IT is hard to learn python by reading. You need to try
coding!
The basic syntax of the Python while loop is,
while <condition>:
<statement(s)>

The line/set of lines to be executed as the loop body is denoted here as <statement(s)>
with the imperative indentation, just as in all python control structures. The <condition>
is the loop controlling condition. It has to be declared and assigned an initial value
before the start of the while loop. Its value is then modified within the loop body to keep
the loop running.
When the loop strats, the <condition> is evaluated in the form of a Boolean expression,
which turns out either to be true or false. The loop body is executed only if the
<condition> is true. If it is evaluated to False , the loop will not be executed at all .As
mentioned before, the loop controlling variable in the <expr> is modified repeatedly
within the lop body and is repeatedly evaluated in each iteration before entering into the
loop body.
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 execute. First we make num to be 5. Then it will check the condition
which is true and procced to execute the loop body. At each iteration it will reduce
number by 1 and finaly when it becomes 0 it will get out of the loop and complete th
code.
Break and Continue statements
Python allows terminating the iteration of the loop prematurely with the break and
continue keywords.
With the break statement, the loop can immediately be terminated in entirety. Once a
break statement is met within the loop ,the loop is exited and the program execution is
passed to the first statement that appears 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 to
take place.
In while loops,

You might also like