[Tutor] 'for' loops

John Fouhy john at fouhy.net
Tue Dec 2 01:56:17 CET 2008


On 02/12/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.
>  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?

I'm not sure exactly what you understand by a "for-next loop".

A for loop, essentially, iterates over a list [1].  e.g.

for fruit in ['apple', 'pear', 'banana', 'tomato']:
    print fruit

The loop will set the variable 'fruit' to be 'apple', 'pear', etc. on
each pass through the loop.

If you just want to do something n times, the usual idiom is:

for i in range(n):
    # do something, possibly involving i

range(n) is a function that will produce the list [0, 1, 2, ..., n-1].

Tutorials should cover this, so I'm not sure if I'm telling you
anything new.  If there's something particular you're stuck on, ask
:-)

-- 
John.

[1] Technically, it iterates over an iterator, which you can think of
as an object that behaves like a list when you throw it at a for loop.


More information about the Tutor mailing list