Python while loop

The Python while loop is use for looping and iteration like the for loop.The difference between while loop and for loop being that for loop iterate over a sequence which gradually end at some points or the sequence have limited number of elements.

Link :Python for loop

The while loop, on the other, hand are not use to iterate over sequence but rather it execute a body of instruction as long as the condition imposed are true.The while loop iteration ends only when the condition is false.

The simplest way to impose a condition on the while loop is to write an expression that returns false automatically when the instruction has been executed the required number of times.

The format of while loop statement is:
 
while expression1 :
#code1

 
The code code1 keeps executing as long as the expression1 returns true.

The example below will print out the integers from 0 to 10.

>>> n=0
>>> while n<11:
	print(n)
	n=n+1

	
0
1
2
3
4
5
6
7
8
9
10

The example is simple,as long as ‘n<11' is true the code "<<< print(n) <<< n=n+1 will keep on executing.When ‘n’ becomes 11 the expression ‘n<11’ is no longer true hence the execution stops.

Here is another example that stores all the odd number from 1 to 10 in a list.

>>> n=1 
>>> odd_list=[]
>>> while n<11:
	if n%2 != 0:
		odd_list.append( n )
	n=n+1

	
>>> odd_list
[1, 3, 5, 7, 9]

To check if a number is odd or not we check the remainder when the number is divided by 2,the expression ‘n%2 != 0’ does this.If the number is odd we add the number to odd_list using the function append().The purpose of append() is to add new elements to list.

More about append() here: List append() method



Why while loop is necessary?

The purpose of for loop is to loop over a sequence.No doubt using while loop we can also iterate over a sequence.The example below loop over a sequence using while loop.

>>> lis=[23 , 'text' , 'happy' , 56 ,78]
>>> tp=(23 , 89 , 89  , 900 , 'New')
>>> lis1=['twenty three' , 'Eighty nine' , 'Nin hundred' , 'N' , 'Fifty six' ]
>>> index=0
>>> while index<len(lis):
	print( lis[index] , ":" , tp[index] , '-' , lis1[index] )
	index+=1

	
23 : 23 - twenty three
text : 89 - Eighty nine
happy : 89 - Nin hundred
56 : 900 - N
78 : New - Fifty six

See we can loop using while loop in a sequence.

What about the vice-versa,i.e. using for loop to execute a code until a condition is fulfilled? yes we can also do with for loop what while loop can do but you will need to think harder than usual and sometimes the result might not be satisfying.

Amidst all these challenges the best way to tackle any programming complexes is to use the right tool for the right job. Use ‘for’ loop whenever sequence are involved and use while loop whenever executing a code under a certain condition is required.

The conclusion is we need both for loop and while loop in Python!!




Leave a Reply

Your email address will not be published. Required fields are marked *