Iterations in programs allow us to perform repetitive tasks in a loop. Let’s have look at the following flow diagram.
Observing the flow diagram:
- A test (expression that evaluates to
True
orFalse
) - If the test is
True
, then execute the loop body once and go back to re-evaluate the test - Repeat until test evaluates to
False
, after which code following iteration statement is executed
Table of Contents
- A simple example of iteration using
while
construct in Python: - A simple example of iteration using
for
construct in Python: - What to use & When?
A simple example of iteration using while
construct in Python:
On execution, the above program prints:
Analysis of the above code:
- First, we declare 3 integer variables,
x
,result
andupper_limit
- In the
while
loop we have a condition, and the code block inside the loop gets executed as long as the condition isTrue
- Inside the code block we add
x
toresult
and incrementx
by 1- We are actually trying to find the sum of first 10 numbers
- As soon as
x
becomes 11, the condition insidewhile
loop evaluated toFalse
and hence the loop breaks - Lastly we print out the sum of first 10 numbers
In programming, a code performing similar task can be written in multiple ways.
For instance, we can write the above code using for
construct as well.
A simple example of iteration using for
construct in Python:
Analysis of the above code:
- Let’s first see how
range()
works
- Now that we know what range does,
for
simple iterates over each value in the the list returned by range and assigns it tox
- Inside the
for
loop we addx
toresult
- Finally, we print out the result
See? How easy it was to perform the same task in a different way.
What to use & When?
- Use
while
when you don’t know the number of times the loop should repeat. It’s only used when you know the condition when loop should break. - Use
for
when you know the fixed number of times the loop should repeat.
Next we will apply the knowledge gained so far to solve an interesting problem. How to find square root of any number?
Note: This is a part of what I learned in an online Open Course Ware offered by MIT on edX. Its for my personal reference & also for those who would like to revisit the course.