[Tutor] More on loops

alan.gauld@bt.com alan.gauld@bt.com
Mon, 8 Apr 2002 16:00:38 +0100


> from livewires import*

for iteration in range(10):
   num1 = random_between(1,10)
   print num1
   raw_input("Press return to exit: ")

This basically says that we are going to set the value 
of iteration to each value of range(10) in turn. For 
each value assignment we will carry out the code thats 
indented.

Thus in the case above we execute your code 10 times.

If we don't know or can't calculate the number of 
iterations in advbance we can use a while loop, like so:

iterate = 'y'
while iterate in 'yY':
   num1 = random_between(1,10)
   print num1
   raw_input("Press return to exit: ")
   iterate = raw_input("Go again(Y/N)? ")


This time we initialise iterate to 'y'.
Then so long as iterate keeps a value of either 'y' or 'Y'
we exectute the indented block, ewhich now includes a 
prompt to set the value of iterate. The user can now 
repeat as oftwen as they like.

If thats still not clear then what exactly don't you 
understand about loops? Can you be specific about 
whats puzzling you?

Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld