On Mon, Dec 01, 2008 at 04:44:02PM -0800, WM. wrote: > I recently asked a question about 'for' loops, expecting them to be > similar to 'for-next' loops. I have looked at several on-line tutors but > am still in the dark about what 'for' loops do. > Does anyone have a plain English about the use of 'for' loops? > Are 'while' loops the only way Python runs a sub-routine over & over?
No, both 'while' and 'for' loops are for running a block of code (whether subroutine calls or whatever) over and over. The difference between the two is that 'while' will continue repeating the block for however many iterations it takes until the condition is satisfied ('while x is true, for some expression x'), a 'for' loop will run the block of code a set number of times ('once for each element of some set of values'). So if you want to execute 'print' for every line of a file, you would do this: for line in file: print line If you wanted to double a value until it exceeded 100, you would use a while loop: while x <= 100: x *= 2 If you just want something executed a specific number of times, (like print "hello" 10 times), you can use a for loop: for i in range(10): print "hello" This is, just like any 'for' loop, executing the block once per element of a list. The list in this case is range(10) which is an expression that generates the list (0, 1, 2, ..., 9), so you get one run through the code for each of those. Does that help? > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Steve Willoughby | Using billion-dollar satellites [EMAIL PROTECTED] | to hunt for Tupperware. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor