[Tutor] 'for' loops

Alan Gauld alan.gauld at btinternet.com
Tue Dec 2 02:17:41 CET 2008


"WM." <wferguson1 at socal.rr.com> 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.

Python for loops are like foreach loops in other languages.
A Python for loop executes a bit of code for each element
in a sequence (list, string, dictionary, set, file etc)
It will keep looping until it runs out of items in the
sequence.

Thus to print each letter in a string:

mystring = 'foobar'
for ch in mystring:
   print ch

Or to print each element of a list:

mlist = [1,'2,'a',45, True]
for item in mylist:
    print item

And if you want to loop for a fixed number of iterations simply 
construct
a list with that number of elements. The range() function does that 
for
us, thus:

for n in range(12):
    print 'hi'

will print 'hi' 12 times.

> 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?

while loops are used much less in Python than in other languages
because for loops are so powerful.
while lops are generally used in cases where you don't know how
many times you need to loop or you want to loop 'forever'.

while True:
    print 'Can't stop me now!'

will keep on looping until you close the program

c = 0
while c != -1:
    c = int(raw_input('Enter a number(-1 to stop) '))
    print c

will keep looping until the user enters -1

More info and a comparison with JabaScript and VBScript can be
found in my tutor in the looping topic.


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list