Iteration

When it comes to programming, you have to make decisions for implementing business logic and iterate a set of statements number of times which again depends on the problem you are solving. We have already seen how decision making works in Python, and now we will move on to the topic of iteration.

Python has :

• while loop
• for loop

Before starting the discussion specifically for loops in Python, let us understand what a loop is or how it works and where to use it.

Let us assume we need to find out prime numbers from 1 to 100. We need to iterate from 1 to 100 one by one to identify whether the current number is a prime number or not a prime number. We need either a variable which has this sequence or a process via which we can generate this sequence at runtime. This sequence could be an array, list, dictionary or any other variable which can be indexed. We traverse the sequence one by one until we reach the end of it, so we need a condition check for the end of the series.

Now let us see how loops in Python works.

WHILE Loop: In this loop, we have a condition check for a looping index, if that condition satisfies the control goes in the loop, executes the statements and manipulate the looping index.

#CODE
index = 1			#defined looping index variable
while index<=10:	#check the condition on looping index
print(index)		#processing inside the loop
index+=1			#manipulting the index variable

#OUTPUT
1
2
3
4
5
6
7
8
9
10

You can also have an else condition after the while loop, which will execute when the loop condition fails. e.g

#CODE

index = 1
while index<=5:
print(index)
index+=1
else :
print("End")

#OUTPUT
1
2
3
4
5
End

FOR Loop: is another looping statement which Python supports, I prefer to use this one because it has more practical usage in implementing business logic. In this, you have to have a sequence or set of data which you need to process, and it takes care of the condition and looping index by itself.

#CODE

total = 0
for itervar in range(1,100):
total += itervar
print( 'Total: ', total)

#OUTPUT

4950

range function gives you a sequence from 1 to 100 (excluded), so the above example gives the sum of numbers from 1 to 99. In for loop the value from the set is assigned to looping index (in this case itervar) one by one in the sequence it is present, and loop executes the statement inside its body.

You might have noticed that there is an indentation in the loop body, the same indentation was there in decision making topic. In Python, you can write the whole code in one line because in this new line is the delimiter for a new statement and indentation makes it a block of statement which makes it a condition block or looping block. 