[Tutor] Re: trouble understanding "for" loops
project5 at redrival.net
Sat Nov 15 06:45:34 EST 2003
<zehoefler at adelphia.net> wrote on Sat, 15 Nov 2003 0:28:36 -0500:
> I was wondering if somebody could explain the "for" loop to me.
> for i in range(10):
> print i,
range(X) is a function which returns a list of values starting at 0 and up
to but not including X. So in this case the loop is equivalent to:
for i in [0,1,2,3,4,5,6,7,8,9]:
What this loop does is this: it takes each element in that list (reading
left to right) and assigns to the variable i the value of that element.
Then it executes the loop code with it - in this case, it means that it
prints i. Note that it's not required to use i inside the loop, you could
just as well 'print 2' if you liked or whatever.
Once the loop code is executed, it picks the next element in the list,
assigns it to i and runs the loop code again. Etc. until it's at the end of
> I noticed that
> it cycles through range... going one number at a time... I mostly
> get it, but I'm still having just a tad bit of trouble. Something
> like "for letter in word:" is printing each letter of the string
> "word" on each line (apparently it inserts line breaks [\n] itself)
Exactly like for letter in word (assuming word is a string). Strings are a
bit like lists of individual chars so you can loop over them in the same
way as you can loop over any other sequence (list, tuple).
> P.S. Is there a way to get the Windows version of IDLE to, when you
> save your script, put the extension '.py' after the strings without
> having to enter it each time. I add the .py so I can access it faster,
> and its a bit tedious.
IDLE is a cross-platform editor. There isn't a 'Windows' version of it as
such. I recommend you look at PythonWin or Scite or Spe which IMO are all
better than IDLE. If you download the ActiveState Python distro, you get
PythonWin installed for you:
You can also get PythonWin from Mark Hammond's Win32 page, but you'll have
to google for it because I don't have the address right now. Scite is at
http://scintilla.org and Spe at http://spe.pycs.net.
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5 at jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.
More information about the Tutor