While loops

FOR loops are a good way of providing iteration into a programming language. There, however, other forms of iteration. While loops can be considered as a more general form of a while loop. Consider the following for loop.


for a in range(0, 11) 
	print a 

# the for in psuedo code
for a = 0 to 10
    print a
next
                    

Here is the equivalent while loop -


a=0 
while a<=10: 
	print A 
	a = a + 1 


                    

 

In order for the loop to occur the condition must evaluate to true. As soon as it evaluates to false the loop will terminate.


temp = "" 
while temp == "" or temp == "error"
	temp = INPUT ("Please enter a number")
	if temp IS NOT NUMBER
		 # this is not valid python line,just using it as a example
		temp == "error"



                    

The above while loop shows how much more flexible while loops can be. The above code will ensure that the user will only ever enter a number. It uses a logical expression which will evaluate to true if the variable temp holds nothing or if it us equal to the text "error" . Putting it simply if the user enters nothing then temp will evaluate to "" (empty string) and the while loop will run again. If the user enters some text then the variable temp will evaluate to "error" and the while loop will again run. If the user enters a number then both temp = "" and temp = "error"will evaluate to false and the WHILE loop will stop. Effectively we have created a very simple error detection (or validation) mechanism. This would not be possible in a FOR loop.

There are two other important differences between a WHILE loop and a FOR loop -

WHILE loops require that the counter be initialized to the starting value manually whilst FOR loops do this automatically (as their start value)

WHILE loops will not automatically increment the counter whilst FOR loops will. WHILE loops require some code which, at some point, will terminate the loop. (force the condition to be false)