Iteration or Looping




Iteration:
Iteration, Repetition, Looping
  • Start with a test
  • If evaluates to True, then execute loop body once, and go back to reevaluate the test
  • Repeat until test evaluates to False, after which code following iteration statement is executed

Taking an example to understand this would be more easy.

x = 1
ans = 0
upto = 10
while (x != upto+1): #looping condition, explained below
    ans = ans + x
    x = x+1 #incrementing x by 1 each time
print 'Sum of first',str(upto),'numbers is',str(ans)
Output:Sum of first 10 numbers is 55 

Line#4: the while loop will be repetitively executed unless x becomes equals to 11. Hence while loop is iterated 10 times for x=1, x=2,.......x=10 and when x=11, condition becomes False & hence execution comes out of while loop & executes the print statement.

In programming we can write code in many different ways. Above code can also be written as.

ans = 0
for x in range(1,11): #range() function explained below
    ans = ans + x
print 'Sum of first',str(x),'numbers is',str(ans)
Output:Sum of first 10 numbers is 55 
 
How range() works:

>>> range(10) #returns a list that contains numbers from 0 to (10-1)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]  #its called a 'list'
>>> range(1,10) #here we forcefully tell range() to start from 1 & end before 10
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1,11)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(1,11,2) # 2 says that it will jump 2 steps. 2 is called 'step argument'
[1, 3, 5, 7, 9]
>>> range(1,11,3) # 3 makes it jump 3 numbers
[1, 4, 7, 10]

Now Line#2: for x in range(1,11):
Since range (1,11) returns a list of numbers from 1 to 10,
So when loop is executed for the first time, x = 1
On 2nd iteration, x = 2...... this goes on & finally after 10th iteration x=10, for loop ends.


What to use & When?


  • Use while when you don't know the number of times the loop should repeat. Its 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.

Note:
This is a part of what I learn in an online Open Course Ware offered by MIT on edX
Its for my personal reference & also for those who have missed the course.
You too can enroll yourself on edX (if they are still offering the course MITx 6.00x)